BoundForGlory
BoundForGlory

Reputation: 4417

Stop file download dialog from showing in Firefox/Chrome

I have an MVC3 app and users can upload files and then view or download them whenever they want. The following code works as expected in IE (my popup window appears and the file in rendered inside of it) but in Firefox i get the open with/save file dialog box and my file doesnt render in the popup window. In chrome, the file just automatically downloads. Heres my code:

   //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();
   }
   }

Heres my view:

    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);
        }

For PDf and plain text files, this works across the board, but for jpg and png files, i get the download dialog. How do I make Firefox/Chrome open files in my popup like they do the PDF files in Firefox/Chrome? Thanks

Upvotes: 0

Views: 2186

Answers (1)

Icarus
Icarus

Reputation: 63956

You need to send some headers so the browser knows how to handle the thing you are streaming. In particular:

Response.ContentType = "image/png"

Response.ContentType = "image/jpg" 

etc.

Also note that for anything different than PDF, you are setting the content-disposition to "Content-Disposition", "application; filename=" + FileName) which will force a download.

Upvotes: 2

Related Questions