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

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)

  • 这是ASP.NET MVC很棒的一个很好的例子.您以前在9行令人困惑的代码中所做的事情可以在一行中完成.这么容易多了! (14认同)

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类型发送,但这会产生下载文件名的问题,因此需要第三个参数来发送一个好的文件名,因此无需强行下载.

  • 从技术上讲,这不是正在发生的事情.从技术上讲,当你添加第三个参数时,MVC框架会添加标题`content-disposition:attachment; filename = MyRenamedFile.pdf` - 这是强制下载的原因.我建议你把MIME类型放回`application/pdf`. (6认同)
  • 谢谢Charlino,我没有意识到第三个参数是这样做的,我认为这只是改变文件名. (2认同)
  • +1用于更新你的答案并解释第三个参数+`Content-Disposition:attachment;`relationship. (2认同)

Ros*_*sim 7

你可以在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