猿问

如何从MVC控制器提供要下载的文件?

如何从MVC控制器提供要下载的文件?

在WebForms中,我通常会有这样的代码让浏览器显示一个“下载文件”弹出窗口,其中包含任意文件类型,如PDF和文件名:


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()

如何在ASP.NET MVC中完成相同的任务?


桃花长相依
浏览 595回答 3
3回答

慕少森

要强制下载PDF文件,而不是由浏览器的PDF插件处理:public ActionResult DownloadPDF(){     return File("~/Content/MyFile.pdf", "application/pdf", "MyRenamedFile.pdf");}如果您想让浏览器按其默认行为(插件或下载)进行处理,只需发送两个参数即可。public ActionResult DownloadPDF(){     return File("~/Content/MyFile.pdf", "application/pdf");}您需要使用第三个参数在浏览器对话框中指定文件的名称。当传递第三个参数(下载文件名)Content-Disposition: attachment;被添加到Http响应标题。我的解决方案是application\force-download作为mime类型发送,但是这会产生下载文件名的问题,因此需要第三个参数来发送一个好的文件名,因此无需强行下载。
随时随地看视频慕课网APP
我要回答