嗨,我正在使用这篇博文中的代码:
https://blog.stephencleary.com/2016/11/streaming-zip-on-aspnet-core.html
为了使用 .Net 核心流式传输 zip 文件。我让它工作了,但是由于我在下载 zip 文件时没有在响应中添加内容长度标头,因此它不会在 chrome 中显示下载进度。由于我事先知道 zip 文件的大小,我实际上可以使用 SetHeadersAndLog 方法设置内容长度标头 https://docs.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",
};