Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In WebForms, I would normally have code like this to let the browser present a "Download File" popup with an arbitrary file type, like a PDF, and a filename:

Response.Clear() Response.ClearHeaders() ''# Send the file to the output stream Response.Buffer = True  Response.AddHeader("Content-Length", pdfData.Length.ToString()) Response.AddHeader("Content-Disposition", "attachment; filename= " & Server.HtmlEncode(filename))  ''# Set the output stream to the correct content type (PDF). Response.ContentType = "application/pdf"  ''# Output the file Response.BinaryWrite(pdfData)  ''# Flushing the Response to display the serialized data ''# to the client browser. Response.Flush() Response.End() 

How do I accomplish the same task in ASP.NET MVC?

like image 311
mgnoonan Avatar asked Apr 08 '09 16:04

mgnoonan


People also ask

How do I save a PDF in MVC?

In my method in controller I use the following code to save pdf. HtmlDocument doc = new HtmlDocument(); doc. LoadHtml(htmlContent); HtmlNode node = doc. GetElementbyId("DetailsToPDF"); HtmlToPdfConverter htmlToPdf = new HtmlToPdfConverter(); var pdfBytes = htmlToPdf.

How do I save a file in MVC?

Use HTML File Upload control. Create HTTPPOST ActionMethod called “ContactForm” to insert record in table and save file in Server. Add Linq To Sql class “ClubMember”. Insert a record into a database table.


2 Answers

Return a FileResult or FileStreamResult from your action, depending on whether the file exists or you create it on the fly.

public ActionResult GetPdf(string filename) {     return File(filename, "application/pdf", Server.UrlEncode(filename)); } 
like image 122
tvanfosson Avatar answered Oct 15 '22 02:10

tvanfosson


To force the download of a PDF file, instead of being handled by the browser's PDF plugin:

public ActionResult DownloadPDF() {     return File("~/Content/MyFile.pdf", "application/pdf", "MyRenamedFile.pdf"); } 

If you want to let the browser handle by its default behavior (plugin or download), just send two parameters.

public ActionResult DownloadPDF() {     return File("~/Content/MyFile.pdf", "application/pdf"); } 

You'll need to use the third parameter to specify a name for the file on the browser dialog.

UPDATE: Charlino is right, when passing the third parameter (download filename) Content-Disposition: attachment; gets added to the Http Response Header. My solution was to send application\force-download as the mime-type, but this generates a problem with the filename of the download so the third parameter is required to send a good filename, therefore eliminating the need to force a download.

like image 27
guzart Avatar answered Oct 15 '22 01:10

guzart