mgn*_*nan 108 asp.net-mvc download
在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()
Run Code Online (Sandbox Code Playgroud)
如何在ASP.NET MVC中完成相同的任务?
tva*_*son 178
返回FileResult
或执行FileStreamResult
操作,具体取决于文件是否存在或您是否即时创建.
public ActionResult GetPdf(string filename)
{
return File(filename, "application/pdf", Server.UrlEncode(filename));
}
Run Code Online (Sandbox Code Playgroud)
guz*_*art 62
要强制下载PDF文件,而不是由浏览器的PDF插件处理:
public ActionResult DownloadPDF()
{
return File("~/Content/MyFile.pdf", "application/pdf", "MyRenamedFile.pdf");
}
Run Code Online (Sandbox Code Playgroud)
如果您想让浏览器按其默认行为(插件或下载)进行处理,只需发送两个参数即可.
public ActionResult DownloadPDF()
{
return File("~/Content/MyFile.pdf", "application/pdf");
}
Run Code Online (Sandbox Code Playgroud)
您需要使用第三个参数在浏览器对话框中指定文件的名称.
更新:Charlino是正确的,当传递第三个参数(下载文件名)Content-Disposition: attachment;
被添加到Http响应标题.我的解决方案是application\force-download
作为mime类型发送,但这会产生下载文件名的问题,因此需要第三个参数来发送一个好的文件名,因此无需强行下载.
你可以在Razor或Controller中做同样的事情,就像这样.
@{
//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");
}
Run Code Online (Sandbox Code Playgroud)
或者在控制器中......
public ActionResult Receipt() {
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");
return View();
}
Run Code Online (Sandbox Code Playgroud)
我在Chrome和IE9中试过这个,都在下载pdf文件.
我可能应该添加我使用RazorPDF来生成我的PDF.这是一个关于它的博客:http://nyveldt.com/blog/post/Introducing-RazorPDF
归档时间: |
|
查看次数: |
103101 次 |
最近记录: |