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?
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.
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.
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)); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With