代码之家  ›  专栏  ›  技术社区  ›  Mike Cole

ASP.NET ASHX处理程序提示下载而不是显示文件

  •  3
  • Mike Cole  · 技术社区  · 14 年前

    我在应用程序中实现了一个通用的处理程序,它对图像非常有用,但是当我用图像的查询字符串在浏览器中手动键入处理程序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();
                    }
                }
            }
    

    我使用的是octet流,因为我处理的不仅仅是图像,我并不总是知道文件的内容类型。提前谢谢!

    3 回复  |  直到 11 年前
        1
  •  6
  •   Pavel Morshenyuk    14 年前

    唯一的方法是指定正确的ContentType,以便浏览器知道如何处理接收文件,这取决于安装的插件(例如,在浏览器框架中查看PDF文件)和系统关联(例如,提供在MS Office中打开文档,而不是简单下载)。

    您可以根据文件扩展名尝试指定内容类型,即:

    if(Path.GetExtension(path) == ".jpg")
       context.Response.ContentType = "image/jpeg";
    else
       context.Response.ContentType = "application/octet-stream";
    
        2
  •  1
  •   Ivan    12 年前

    如果你储存 ContentType 作为文件元数据的一部分,当您将其拉回时,可以使用它。

    theFile = GetFile(id)
    context.Response.ContentType = theFile.Type;
    
        3
  •  -1
  •   ZippyV    14 年前

    Content Disposition头会导致浏览器显示下载对话框。删除该行,它将显示在浏览器中。