Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC download image rather than display in browser

Rather than displaying a PNG in the browser window, I'd like the action result to trigger the file download dialogue box (you know the open, save as, etc). I can get this to work with the code below using an unknown content type, but the user then has to type in .png at the end of the file name. How can I accomplish this behavior without forcing the user to type in the file extension?

    public ActionResult DownloadAdTemplate(string pathCode)     {         var imgPath = Server.MapPath(service.GetTemplatePath(pathCode));         return base.File(imgPath, "application/unknown");     } 

Solution....

    public ActionResult DownloadAdTemplate(string pathCode)     {         var imgPath = Server.MapPath(service.GetTemplatePath(pathCode));         Response.AddHeader("Content-Disposition", "attachment;filename=DealerAdTemplate.png");         Response.WriteFile(imgPath);         Response.End();         return null;     } 
like image 943
RSolberg Avatar asked Jun 09 '10 16:06

RSolberg


People also ask

Is ASP NET MVC discontinued?

ASP.NET MVC is no longer in active development. The last version update was in November 2018. Despite this, a lot of projects are using ASP.NET MVC for web solution development. As to JetBrains' research, 42% of software developers were using the framework in 2020.

Where are images stored in ASP NET MVC?

Images are stored in /Content/Images.

What is meaning of @: In .NET MVC?

Using @: to explicitly indicate the start of content We are using the @: character sequence to explicitly indicate that this line within our code block should be treated as content.


2 Answers

You need to set the following headers on the response:

  • Content-Disposition: attachment; filename="myfile.png"
  • Content-Type: application/force-download
like image 32
Aren Avatar answered Oct 05 '22 23:10

Aren


I believe you can control this with the content-disposition header.

Response.AddHeader(        "Content-Disposition", "attachment; filename=\"filenamehere.png\"");  
like image 133
womp Avatar answered Oct 05 '22 23:10

womp