如何从MVC控制器呈现文件下载? [英] How can I present a file for download from an MVC controller?

查看:99
本文介绍了如何从MVC控制器呈现文件下载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WebForms中,我通常会有这样的代码,让浏览器提供一个任意文件类型的下载文件弹出窗口,如PDF和文件名:

In WebForms, I would normally have code like this to let the browser present a "Download File" popup with an arbitrary file type, like a PDF, and a filename:

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

How do I accomplish the same task in ASP.NET MVC?

推荐答案

返回一个 FileResult FileStreamResult ,具体取决于该文件是否存在,或者是您即时创建。

Return a FileResult or FileStreamResult from your action, depending on whether the file exists or you create it on the fly.

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

这篇关于如何从MVC控制器呈现文件下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆