我怎样才能present从MVC控制器用于下载的文件? [英] How can I present a file for download from an MVC controller?

查看:105
本文介绍了我怎样才能present从MVC控制器用于下载的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在的WebForms,我通常有code这样让浏览器present一个下载文件弹出一个任意文件类型,如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));
}

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

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