我实现我的应用程序的通用处理器,其能很好的完成图像,但是当我手动与图像的查询字符串键入URL处理程序在浏览器中它会提示下载,而不是显示的。这里是我的代码:asp.net ashx的处理程序提示下载,而不是显示文件
public void ProcessRequest(HttpContext context)
{
if (this.FileName != null)
{
string path = Path.Combine(ConfigurationManager.UploadsDirectory, this.FileName);
if (File.Exists(path) == true)
{
FileStream file = new FileStream(path, FileMode.Open);
byte[] buffer = new byte[(int)file.Length];
file.Read(buffer, 0, (int)file.Length);
file.Close();
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("content-disposition", "attachment; filename=\"" + this.FileName + "\"");
context.Response.BinaryWrite(buffer);
context.Response.End();
}
}
}
我使用的,因为我负责的不仅仅是图像更加的八位字节流,我总是不知道该文件的内容类型。提前致谢!
我会硬编码的几个明显的情况下,例如jpg - > image/jpeg,那么您可以从注册表中查找其余的内容,例如在这个问题的代码http://stackoverflow.com/questions/3442607/mime-types-in-the-windows-registry。 (虽然我会在应用中保留一个本地缓存,因为我很紧张从.NET注册到注册表将是一个昂贵的操作) – Rup 2010-08-10 18:34:54
@RUP关于使用注册表的好主意! – 2010-08-10 18:42:20
这就是IIS所做的。尽管正如在我连接服务器的问题中,通常缺少用于例如.pdf或.flv(这是我过去烧的那个)。 – Rup 2010-08-10 18:44:32