在WebForms中,我通常会有这样的代码,让浏览器显示一个带有任意文件类型和文件名的“下载文件”弹出窗口:
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中完成相同的任务?
发布于 2009-04-08 16:24:47
从您的操作中返回一个FileResult
或FileStreamResult
,这取决于文件是存在的还是您动态创建的。
public ActionResult GetPdf(string filename)
{
return File(filename, "application/pdf", Server.UrlEncode(filename));
}
发布于 2013-05-24 09:21:26
您可以在Razor或控制器中执行相同的操作,如下所示。
@{
//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和IE9上试过了,都在下载pdf文件。
我可能应该补充说,我正在使用RazorPDF生成我的PDF。这里有一个关于它的博客:http://nyveldt.com/blog/post/Introducing-RazorPDF
发布于 2009-04-08 16:22:59
您应该查看控制器的File方法。这正是它的作用所在。它返回一个FilePathResult而不是一个ActionResult。
https://stackoverflow.com/questions/730699
复制相似问题