0

我有一个 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 文件一样?谢谢

4

1 回答 1

2

您需要发送一些标头,以便浏览器知道如何处理您正在流式传输的内容。尤其:

Response.ContentType = "image/png"

Response.ContentType = "image/jpg" 

等等

另请注意,对于与 PDF 不同的任何内容,您正在设置 "Content-Disposition", "application; filename=" + FileName)将强制下载的内容处置。

于 2012-06-07T14:28:29.477 回答