[英]ASHX image handler works with chrome, not IE8
我已经创建了使用ASHX处理程序从文件系统检索图像的代码。 该代码在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类型。 以下是一些常见的图像哑剧类型,这些函数来自旨在返回文件的相应哑剧类型的函数:
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);
当然,正如我之前说过的,如果您没有文件的物理路径(例如,如果文件存储在数据库中),您仍然应该知道图像类型。
希望这可以帮助,
安德烈
IE确实需要Mime类型。
以下是我用来获取图像的mime类型,或将其强制为常规文件并由系统处理的情况。
objMIMEType = Microsoft.Win32.Registry.GetValue("HKEY_CLASSES_ROOT\\." + objAttachment.Extension, "Content Type", "application/octetstream");
if (objMIMEType != null)
strMIMEType = objMIMEType.ToString();
else
{
strMIMEType = "application/octetstream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + objAttachment.FullFileName);
context.Response.AddHeader("Content-Length", objAttachment.AttachmentData.Length.ToString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.