我在我的应用程序中实现了一个非常适用于图像的通用处理程序,但是当我在浏览器中使用图像的查询字符串手动键入处理程序URL时,它会提示下载而不是显示.这是我的代码:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用八位字节流,因为我处理的不仅仅是图像,我并不总是知道文件的内容类型.提前致谢!
唯一的方法是指定正确的ContentType,以便浏览器知道如何处理接收文件,具体取决于安装的插件(例如,查看浏览器框架中的pdf文件)和系统协议(例如,提供在MS Office中打开文档而不是简单下载)
您可以尝试根据文件扩展名指定内容类型,即:
if(Path.GetExtension(path) == ".jpg")
context.Response.ContentType = "image/jpeg";
else
context.Response.ContentType = "application/octet-stream";
Run Code Online (Sandbox Code Playgroud)