2015-06-21 57 views
0

我正在嘗試使用ashx從數據庫加載圖像。使用ashx閱讀圖像在asp.net中不起作用

當我使用此代碼的圖像加載成功

<% <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Id", "~/Handler/CategoryHandler.ashx?catId={0}") %>' /> 

但是,當我使用此代碼

<% 
      foreach (ProductCategories VARIABLE in categoriesList) 
      { 
       Response.Write("<div class='wrapper-box'>" + 
            "<a href='product/product.aspx'>" + 
             "<img src='~/Handler/ProductHandler.ashx?Id="+VARIABLE.Id+"'/>" + 
             "<p>"+VARIABLE.CategoryName+"</p>" + 
            "</a>" + 
           "</div>"); 
      } 

      %> 

圖像不會加載。爲什麼代碼不能正常工作?

的ashx的文件是這樣的:

public void ProcessRequest(HttpContext context) 
    { 
     // Set up the response settings 
     context.Response.ContentType = "image/jpeg"; 
     context.Response.Cache.SetCacheability(HttpCacheability.Public); 
     context.Response.BufferOutput = false; 
     // Setup the Size Parameter 
     ImageSize size; 
     switch (context.Request.QueryString["Size"]) 
     { 
      case "S": 
       size = ImageSize.Small; 
       break; 
      case "L": 
       size = ImageSize.Large; 
       break; 
      default: 
       size = ImageSize.Small; 
       break; 
     } 
     // Setup the PhotoID Parameter 
     Stream stream; 
     if (context.Request.QueryString["Id"] != null && context.Request.QueryString["Id"] != "") 
     { 
      Int32 id = Convert.ToInt32(context.Request.QueryString["Id"]); 
      stream = Products.GetImageStream(id, size); 
      //context.Response.AddHeader("content-disposition", String.Format("attachement;filename=\"{0}\"",); 
      // Get the photo from the database, if nothing is returned, get the default "placeholder" photo 
      if (stream == null) return; 
      // Write image stream to the response stream 
      const int buffersize = 1024 * 16; 
      byte[] buffer = new byte[buffersize]; 
      int count = stream.Read(buffer, 0, buffersize); 
      while (count > 0) 
      { 
       context.Response.OutputStream.Write(buffer, 0, count); 
       count = stream.Read(buffer, 0, buffersize); 
      } 
     } 
    } 

回答

1

的問題是,Response.Write不擴大~字符到基本URL,從而在頁面的HTML生成的圖像的URL是與此類似:

<img src='~/Handler/ProductHandler.ashx?Id=123' /> 

爲了解決這個問題,你有你的Response.Write使用前擴大網址:

<% 
    foreach (ProductCategories VARIABLE in categoriesList) 
    { 
     var imgUrl = ResolveUrl("~/Handler/ProductHandler.ashx?Id=" + VARIABLE.Id.ToString()); 
     Response.Write("<div class='wrapper-box'>" + 
      "<a href='product/product.aspx'>" + 
       "<img src='" + imgUrl + "'/>" + 
       "<p>"+VARIABLE.CategoryName+"</p>" + 
      "</a>" + 
     "</div>"); 
} 
%> 
+0

它不工作親愛的朋友。 –

+0

圖像保存在數據庫中圖像字段 –

+0

圖像無法加載! –