我已经创建了使用 ASSX 处理程序从文件系统检索图像的代码。该代码在 Chrome 中正确显示图像,但在 IE 中显示图像损坏:
public class ImageHandler : IHttpHandler
{
private int? QS_ImageID
{
get
{
int? temp = null;
if (HttpContext.Current.Request.QueryString["ImageID"] != null)
temp = HA.Utility.DataHelper.ParseDbInt(HttpContext.Current.Request.QueryString["ImageID"]);
return temp;
}
}
private bool QS_Thumbnail
{
get
{
bool thumbNail = false;
if (HttpContext.Current.Request.QueryString["Thumbnail"] != null)
{
if (HttpContext.Current.Request.QueryString["Thumbnail"].Equals("1"))
thumbNail = true;
}
return thumbNail;
}
}
public void ProcessRequest(HttpContext context)
{
if (QS_ImageID.HasValue)
{
int uploadID = QS_ImageID.Value;
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.Cache.SetNoStore();
context.Response.ContentType = UploadDAL.GetMetaData(uploadID).UploadContentType;
context.Response.AddHeader("Content-Disposition", "inline;");
if (QS_Thumbnail)
{
byte[] myImage = UploadDAL.GetFileThumbNail(uploadID);
context.Response.AddHeader("Content-Length", myImage.GetLength(0).ToString());
context.Response.BinaryWrite(myImage);
context.Response.End();
}
else
{
byte[] myImage = UploadDAL.GetFile(uploadID);
context.Response.AddHeader("Content-Length", myImage.GetLength(0).ToString());
context.Response.BinaryWrite(myImage);
context.Response.End();
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
最佳答案
问题可能是您没有为文件指定 mime 类型。以下是一些常见的图像 MIME 类型,来自旨在返回文件相应 MIME 类型的函数:
string getContentType(String path) { switch (Path.GetExtension(path)) { case ".bmp": return "Image/bmp"; case ".gif": return "Image/gif"; case ".jpg": return "Image/jpeg"; case ".png": return "Image/png"; default : break; } return ""; }
如果图像物理存储在硬盘上,您可以按原样使用这段代码,如果不是的话,至少它可以让您了解如何确定 mime 类型。
在 ProcessRequest
方法中,您可以使用
context.Response.ContentType = getContentType(imageFileName);
当然,正如我之前所说,如果您没有文件的物理路径(例如,如果它存储在数据库中),您仍然应该知道图像类型。
希望这有帮助,
安德烈
关于c# - ASHX 图像处理程序适用于 Chrome,不适用于 IE8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3327605/