0

I found this link. ASP.NET MVC download image rather than display in browser

I tried everything and my action method dumps the file into the view instead of downloading. I would like to be able to download the file separately. Thanks

        if (extension.ToLower() == ".docx")
        { // Handle *.jpg and   
            contentType = "application/docx";
        }
        else if (extension.ToLower() == ".jpg")
        {// Handle *.gif   
            contentType = "image/jpeg jpeg jpg jpe";
        }
        else if (extension.ToLower() == ".pdf")
        {// Handle *.pdf   
            contentType = "application/pdf";
        }
        Response.ContentType = contentType; // "application/force-download";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
        Response.WriteFile(FilePath );
        Response.Flush();
        Response.End();[![View after clicking download button][1]][1]
Community
  • 1
  • 1
lama
  • 65
  • 1
  • 11

1 Answers1

0

Your problem is probably similar with these:

How can I present a file for download from an MVC controller?

Returning a file to View/Download in ASP.NET MVC

Instead of using Response.WriteFile, you can return FileResult or FileStreamResult from action method by using this code:

    if (extension.ToLower() == ".docx")
    { // Handle *.jpg and   
        contentType = "application/docx";
    }
    else if (extension.ToLower() == ".jpg")
    {// Handle *.gif   
        contentType = "image/jpeg jpeg jpg jpe";
    }
    else if (extension.ToLower() == ".pdf")
    {// Handle *.pdf   
        contentType = "application/pdf";
    }
    Response.ContentType = contentType; // "application/force-download";
    Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);

    // returning the file for download as FileResult
    // third input parameter is optional
    return File(FileName, contentType, Server.UrlEncode(Filename));

NB: As Leo said in https://stackoverflow.com/a/36776089/6378815, Response.AppendHeader method may cause browser to fail rendering the file content if the response header already contains Content-Disposition section. You may want try this way:

Response.Headers.Add("Content-Disposition", "attachment; filename=" + FileName);

Additional reference:

Response.WriteFile() -- not working asp net mvc 4.5

Community
  • 1
  • 1
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61