我该如何在MVC控制器中呈现一个可供下载的文件?

110

在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()

我该如何在ASP.NET MVC中完成同样的任务?

7个回答

184

根据文件是否存在或动态创建的情况,从您的操作中返回一个FileResultFileStreamResult

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

1
这需要在文件名上加上文件扩展名,否则它将完全忽略文件名和内容类型,并尝试将文件流式传输到浏览器。如果浏览器在强制下载时无法识别内容类型(即八位字节流),它也将仅使用网页名称,并且根本没有扩展名。 - RichC

63

为了强制下载PDF文件而不是由浏览器的PDF插件处理:

public ActionResult DownloadPDF()
{
    return File("~/Content/MyFile.pdf", "application/pdf", "MyRenamedFile.pdf");
}

如果您希望让浏览器按照其默认行为处理(插件或下载),只需发送两个参数。

public ActionResult DownloadPDF()
{
    return File("~/Content/MyFile.pdf", "application/pdf");
}

你需要使用第三个参数在浏览器对话框中指定文件名称。

更新:Charlino是正确的,当传递第三个参数(下载文件名)时,Content-Disposition: attachment;会被添加到Http响应头中。我的解决方案是将application\force-download发送为mime类型,但这会引发下载文件名称的问题,因此需要使用第三个参数发送一个良好的文件名,从而消除了强制下载的必要性。


6
从技术上讲,这不是正在发生的事情。从技术上讲,当您添加第三个参数时,MVC框架会添加标题content-disposition: attachment; filename=MyRenamedFile.pdf - 这就是强制下载的原因。我建议您将MIME类型改回application/pdf - Charlino
2
谢谢Charlino,我没有意识到第三个参数是干这个的,我以为它只是用来改文件名的。 - guzart

8
您可以在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


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

3

你可以按照以下方式返回一个FileStream:

/// <summary>
/// Creates a new Excel spreadsheet based on a template using the NPOI library.
/// The template is changed in memory and a copy of it is sent to
/// the user computer through a file stream.
/// </summary>
/// <returns>Excel report</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult NPOICreate()
{
    try
    {
        // Opening the Excel template...
        FileStream fs =
            new FileStream(Server.MapPath(@"\Content\NPOITemplate.xls"), FileMode.Open, FileAccess.Read);

        // Getting the complete workbook...
        HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);

        // Getting the worksheet by its name...
        HSSFSheet sheet = templateWorkbook.GetSheet("Sheet1");

        // Getting the row... 0 is the first row.
        HSSFRow dataRow = sheet.GetRow(4);

        // Setting the value 77 at row 5 column 1
        dataRow.GetCell(0).SetCellValue(77);

        // Forcing formula recalculation...
        sheet.ForceFormulaRecalculation = true;

        MemoryStream ms = new MemoryStream();

        // Writing the workbook content to the FileStream...
        templateWorkbook.Write(ms);

        TempData["Message"] = "Excel report created successfully!";

        // Sending the server processed data back to the user computer...
        return File(ms.ToArray(), "application/vnd.ms-excel", "NPOINewFile.xls");
    }
    catch(Exception ex)
    {
        TempData["Message"] = "Oops! Something went wrong.";

        return RedirectToAction("NPOI");
    }
}

1
尽管标准的操作结果FileContentResult或FileStreamResult可用于下载文件,但为了重复使用性,创建自定义操作结果可能是最佳解决方案。
例如,让我们创建一个自定义操作结果,以便在下载时将数据导出到Excel文件中。
ExcelResult类继承自抽象的ActionResult类,并覆盖ExecuteResult方法。
我们使用FastMember包从IEnumerable对象创建DataTable,使用ClosedXML包从DataTable创建Excel文件。
public class ExcelResult<T> : ActionResult
{
    private DataTable dataTable;
    private string fileName;

    public ExcelResult(IEnumerable<T> data, string filename, string[] columns)
    {
        this.dataTable = new DataTable();
        using (var reader = ObjectReader.Create(data, columns))
        {
            dataTable.Load(reader);
        }
        this.fileName = filename;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context != null)
        {
            var response = context.HttpContext.Response;
            response.Clear();
            response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            response.AddHeader("content-disposition", string.Format(@"attachment;filename=""{0}""", fileName));
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dataTable, "Sheet1");
                using (MemoryStream stream = new MemoryStream())
                {
                    wb.SaveAs(stream);
                    response.BinaryWrite(stream.ToArray());
                }
            }
        }
    }
}

在控制器中使用自定义的ExcelResult操作结果,如下所示。
[HttpGet]
public async Task<ExcelResult<MyViewModel>> ExportToExcel()
{
    var model = new Models.MyDataModel();
    var items = await model.GetItems();
    string[] columns = new string[] { "Column1", "Column2", "Column3" };
    string filename = "mydata.xlsx";
    return new ExcelResult<MyViewModel>(items, filename, columns);
}

由于我们使用 HttpGet 下载文件,因此创建一个没有模型和空布局的空视图。
关于动态创建文件的自定义操作结果的博客文章:

https://acanozturk.blogspot.com/2019/03/custom-actionresult-for-files-in-aspnet.html


-4
请使用 .ashx 文件类型并使用相同的代码。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接