2023-02-17 378
在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中完成相同的任务?
返回 FileResult 或 FileStreamResult 从您的动作中,取决于文件是否存在或您即时创建.
public ActionResult GetPdf(string filename)
{
return File(filename, "application/pdf", Server.UrlEncode(filename));
}
强制下载PDF文件,而不是由浏览器的PDF插件处理:
public ActionResult DownloadPDF()
{
return File("~/Content/MyFile.pdf", "application/pdf", "MyRenamedFile.pdf");
}
如果要让浏览器通过其默认行为(插件或下载)来处理,请发送两个参数.
public ActionResult DownloadPDF()
{
return File("~/Content/MyFile.pdf", "application/pdf");
}
您需要使用第三个参数来指定”浏览器”对话框中该文件的名称.
更新:Charlino是正确的,当传递第三个参数(下载文件名)Content-Disposition: attachment;被添加到HTTP响应标头中.我的解决方案是将application\force-download发送为Mime-Type,但这会引起下载文件名的问题,因此第三个参数需要发送一个好的文件名,因此消除了强制下载.
您可以在剃须刀或控制器中执行相同的操作.
@{
//do this on the top most of your View, immediately after `using` statement
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");
}
或在控制器中.
public ActionResult Receipt() {
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");
return View();
}
我在Chrome and IE9中尝试了此操作,都在下载PDF文件.
我可能应该添加我正在使用 razorpdf 生成我的pdfs.这是一个有关它的博客:
以上所述是小编给大家介绍的我怎样才能从MVC控制器中展示一个供下载的文件?,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!
原文链接:https://77isp.com/post/34222.html
=========================================
https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。
数据库技术 2022-03-28
网站技术 2022-11-26
网站技术 2023-01-07
网站技术 2022-11-17
Windows相关 2022-02-23
网站技术 2023-01-14
Windows相关 2022-02-16
Windows相关 2022-02-16
Linux相关 2022-02-27
数据库技术 2022-02-20
抠敌 2023年10月23日
嚼餐 2023年10月23日
男忌 2023年10月22日
瓮仆 2023年10月22日
簿偌 2023年10月22日
扫码二维码
获取最新动态