如何提供从 MVC 控制器下载的文件? [英] How can I present a file for download from an MVC controller?
本文介绍了如何提供从 MVC 控制器下载的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 WebForms 中,我通常会有这样的代码,让浏览器显示下载文件"弹出窗口,其中包含任意文件类型,如 PDF 和文件名:
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()
如何在 ASP.NET MVC 中完成相同的任务?
How do I accomplish the same task in ASP.NET MVC?
推荐答案
返回一个 FileResult
或 FileStreamResult
来自您的操作,具体取决于文件是否存在或您即时创建.
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));
}
这篇关于如何提供从 MVC 控制器下载的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文