Fra*_*eau 1 c# http content-length fileresult .net-core
您好,我使用这篇博文中的代码:
https://blog.stephencleary.com/2016/11/streaming-zip-on-aspnet-core.html
为了使用 .Net core 传输 zip 文件。我成功了,但由于我下载 zip 文件时没有在响应中添加内容长度标头,因此它不会在 chrome 中显示下载进度。因为我提前知道 zip 文件大小,所以我实际上可以使用 SetHeadersAndLog 方法设置内容长度标头 https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.internal.fileresultexecutorbase .setheadersandlog?view=aspnetcore-2.0
但是当我这样做时出现以下错误:
System.InvalidOperationException: Response Content-Length mismatch: too many bytes written (144144633 of 144144627)。
知道为什么响应的长度与 zip 文件的长度不同吗?这是提供该文件的代码:
this._httpContext.Response.ContentType = "application/octet-stream";
this._httpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
this._httpContext.Response.ContentLength = estimatedFileSize;
FileCallbackResult result = new FileCallbackResult(new MediaTypeHeaderValue("application/octet-stream"), estimatedFileSize, async (outputStream, _) =>
{
using (ZipArchive zip = new ZipArchive(outputStream, ZipArchiveMode.Create, false))
{
foreach (string filepath in Directory.EnumerateFiles(existingDirectory.FullName, "*.*", SearchOption.AllDirectories))
{
string relativepath = filepath.Replace(existingDirectory.FullName + "\\", string.Empty);
ZipArchiveEntry zipEntry = zip.CreateEntry(relativepath, CompressionLevel.Fastest);
using (Stream zipstream = zipEntry.Open())
{
using (Stream stream = new FileStream(filepath, FileMode.Open))
{
await stream.CopyToAsync(zipstream);
}
}
}
}
})
{
FileDownloadName = $"{package.FileName}.zip",
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6287 次 |
| 最近记录: |