停止在Firefox / Chrome中显示文件下载对话框

时间:2012-06-07 14:21:53

标签: c# asp.net-mvc-3

我有一个MVC3应用程序,用户可以上传文件,然后随时查看或下载它们。以下代码在IE中按预期工作(我的弹出窗口出现,文件在其中呈现)但在Firefox中我得到打开的/保存文件对话框,我的文件在弹出窗口中不呈现。在chrome中,文件只是自动下载。继承我的代码:

   //for brevity i'm not showing how i get the file stream to display, 
   //but that code works fine, also the ContentType is set properly as well

       public class BinaryContentResult : ActionResult
    {


    private readonly string ContentType;
    private readonly string FileName;
    private readonly int Length;
    private readonly byte[] ContentBytes;

        public BinaryContentResult(byte[] contentBytes, string contentType, string fileName, int nLength)
    {
        ContentBytes = contentBytes;
        ContentType = contentType;
        FileName = fileName;
        Length = nLength;
    }
    public override void ExecuteResult(ControllerContext context)
   {
        var response = context.HttpContext.Response; //current context being passed in
        response.Clear();
        response.Cache.SetCacheability(HttpCacheability.NoCache);
        response.ContentType = ContentType;

        if (ext.ToLower().IndexOf(".pdf") == -1)
        {
            //if i comment out this line, jpg files open fine but not png
            response.AddHeader("Content-Disposition", "application; filename=" + FileName);
            response.AddHeader("Content-Length", Length.ToString());

            response.ContentEncoding = System.Text.Encoding.UTF8;
        }

        var stream = new MemoryStream(ContentBytes); //byte[] ContentBytes;
        stream.WriteTo(response.OutputStream);
        stream.Dispose();
   }
   }

继承我的观点:

    public ActionResult _ShowDocument(string id)
    { 

        int nLength = fileStream.Length;//fileStream is a Stream object containing the file to display

         return new BinaryContentResult(byteInfo, contentType, FileName,nLength);
        }

对于PDf和纯文本文件,这是全面的,但对于jpg和png文件,我得到了下载对话框。如何在我的弹出窗口中创建Firefox / Chrome打开文件,就像他们在Firefox / Chrome中执行PDF文件一样?感谢

1 个答案:

答案 0 :(得分:2)

您需要发送一些标题,以便浏览器知道如何处理您正在传输的内容。特别是:

Response.ContentType = "image/png"

Response.ContentType = "image/jpg" 

另请注意,对于与PDF不同的内容,您要将内容处置设置为"Content-Disposition", "application; filename=" + FileName),这将强行下载。