Search code examples
c#filestreamasp.net-3.5

file extension not downloading in ASP.NET 3.5 forms


I'm really baffled because on one website, my code works perfectly, and on another website, it doesn't.

The file downloads without the extension, but when I rename the downloaded file to include the extension (I add .pdf to the filename), it opens correctly as a PDF. I am 100% sure bytes and filename are correct, and filename is report.pdf.

Here's the original code:

    private void downloadByteStreamAsFile(Byte[] bytes, String fileName)
    {
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.Clear();

            //response.Flush(); //comment this or else no file returned
            response.AddHeader("Content-Type", "binary/octet-stream");
            response.AddHeader("Content-Disposition",
                "attachment; filename=" + fileName + "; size=" + bytes.Length.ToString());

            response.BinaryWrite(bytes);
            response.Flush();
            response.End();

        }
    }

I also tried:

Please help

Update: Code works fine in IE and Chrome, only Firefox has this issue of losing the file extension


Solution

  • This threw me for a real loop, but it turned out that only PDF files weren't being downloaded correctly, and that was because of the Content-Type being set. I probably could have refactored my code differently, but I liked coding it this way best because it was easiest for me to understand and debug. Here's my fixed method:

        private void downloadByteStreamAsFile(Byte[] bytes, String fileName)
        {
            fileName = fileName.Replace(" ", "_");
    
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
    
           if( fileName.Contains(".pdf")){
                fileName = HttpUtility.UrlEncode(fileName);
                //response.Flush(); //comment this or else no file returned
                response.AddHeader("Content-Type", "application/pdf");
                response.AddHeader("Content-Disposition",
                    "attachment; filename=" + fileName + "; size=" + bytes.Length.ToString());
    
                response.BinaryWrite(bytes);
                response.Flush();
                response.End();
            } else {
                //response.Flush(); //comment this or else no file returned
                response.AddHeader("Content-Type", "binary/octet-stream");
                response.AddHeader("Content-Disposition",
                    "attachment; filename=" + fileName + "; size=" + bytes.Length.ToString());
    
                response.BinaryWrite(bytes);
                response.Flush();
                response.End();
    
            }
        }