2012-01-27 45 views
0

我正在使用ashx文件從數據庫中檢索圖像。 如果它在數據庫中不可用,它會顯示在我的 項目文件夾中的另一個圖像。但我無法訪問本地圖像。 任何人都可以幫我或建議一些東西嗎?在asp.net中通過.ashx訪問本地圖像

我的代碼:

public void ProcessRequest (HttpContext context) 
{ 
    context.Response.ContentType = "text/plain"; 
    string Value = (string)context.Session["UserID"]; 
    Stream strm = ShowEmpImage(Value); 
    if (strm == null) 
    { 
     byte[] imageBytes = File.ReadAllBytes("~/images/photo_not_available.png" + context.Request["image"]); 
     context.Response.ContentType = "image/png"; 
     context.Response.BinaryWrite(imageBytes);   
    } 
    else 
    { 
     byte[] buffer = new byte[4096]; 
     int byteSeq = strm.Read(buffer, 0, 4096); 

     while (byteSeq > 0) 
     { 
      context.Response.OutputStream.Write(buffer, 0, byteSeq); 
      byteSeq = strm.Read(buffer, 0, 4096); 
     } 
    } 
    //context.Response.BinaryWrite(buffer); 
} 

ThnnQ

回答

1

您可以使用HttpResponse.TransmitFile方法

Response.TransmitFile(context.Request.MapPath("~/images/photo_not_available.png")); 
+0

感謝您的respond.But它顯示像「名‘服務器’的錯誤不存在於當前上下文中「 – 2012-01-27 12:56:00

+0

@SantoshSahu使用context.Responce.TransmitFile調用它不要等待所有事情都由其他人解決,開始思考你的代碼。 – Aristos 2012-01-27 13:00:27

+0

感謝您的好解決方案。 – 2017-01-24 16:47:28

2

爲了確保您在這裏有一個bug,添加在圖像文件名,一個更變量 - 這肯定是一個不存在的文件。

byte[] imageBytes = 
File.ReadAllBytes("~/images/photo_not_available.png" + context.Request["image"]); 

這裏第二個錯誤是,你不要讓你的〜

byte[] imageBytes = File.ReadAllBytes(
content.Request.MapPath("~/images/photo_not_available.png")); 

的MapPath或者你可以把它作爲@zapthedingbat建議。

還有一個問題,你開始

context.Response.ContentType = "text/plain"; 

,然後將其更改爲

context.Response.ContentType = "image/png"; 
+0

謝謝您的快速回復。但我曾試過這個東西,但它顯示「無法找到路徑的一部分」C:\ Program Files \ Common Files \ MicrosoftShared \ DevServer \ 10.0 \〜\ images \ photo_not_available.png'。「 – 2012-01-27 13:00:51

+0

@SantoshSahu正確,因爲你使用了符號〜但是這個函數沒有修復路徑 - 這是第二個錯誤。 – Aristos 2012-01-27 13:02:28

+0

感謝您的幫助。 雅沒有顯示任何錯誤。但是我的圖片沒有顯示在aspx頁面中。你能建議我在哪裏製造Bug。 – 2012-01-27 13:10:18