首页 > 解决方案 > 从 webapp 下载 zip 文件

问题描述

我的 webapp 的用户应该能够下载超过 10MB 的 zip 文件。我的控制器中有以下代码:

[HttpPost]
public IActionResult Download(){
    Response.Clear();
    esponse.Headers.Add("Content-disposition", "attachment; filename=" + filename +".zip");
    Response.ContentType = "application/zip";
    Response.SendFileAsync(pathOfTheFile);
    Response.Body.FlushAsync();

    return Content("Download successfull");
}

它开始下载文件,但下载停止并显示网络错误。当我在下载栏中说继续时,它说没有文件。

我的问题是什么?

标签: c#asp.netasp.net-mvcasp.net-core

解决方案


发生错误是因为带有标题和内容的响应被写入了两次。第一次是由您的代码编写的Response.Body.FlushAsync,第二次ASP.NET是在执行动作返回的结果时由框架编写的(IActionResult.ExecuteResultAsync)。

考虑使用File提供的方法Controller

[HttpPost]
public IActionResult Download()
{
    byte[] content = System.IO.File.ReadAllBytes(pathOfTheFile);

    return File(content, "application/zip", filename);
}

推荐阅读