首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何显示要从MVC控制器下载的文件?

如何显示要从MVC控制器下载的文件?
EN

Stack Overflow用户
提问于 2009-04-08 16:07:17
回答 6查看 112.8K关注 0票数 110

在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中完成相同的任务?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2009-04-08 16:24:47

从您的操作中返回一个FileResultFileStreamResult,这取决于文件是存在的还是您动态创建的。

public ActionResult GetPdf(string filename)
{
    return File(filename, "application/pdf", Server.UrlEncode(filename));
}
票数 183
EN

Stack Overflow用户

发布于 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

票数 7
EN

Stack Overflow用户

发布于 2009-04-08 16:22:59

您应该查看控制器的File方法。这正是它的作用所在。它返回一个FilePathResult而不是一个ActionResult。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/730699

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档