我尝试在内存中创建一个zip文件,从文件流中读取多个其他zip文件。它似乎能够正确读取文件,并创建一个zip文件;但是,在创建响应时,所有内容标头都会放入invalidHeaders
。这会导致永远不会发生下载,而是加载了错误的响应页面。
using (var memoryStream = new MemoryStream())
{
// Gather all zips into a single zip file
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
foreach(var zipFile in zipFiles)
{
archive.CreateEntryFromFile(zipFile.ZipFilePath, Path.GetFileName(zipFile.ZipFilePath));
}
}
// Now we have our memory stream with our zip
HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.OK);
message.Content = new StreamContent(memoryStream);
message.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
message.Content.Headers.ContentDisposition.FileName = "AllZIPFiles.zip";
message.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
message.Content.Headers.ContentLength = memoryStream.Length;
// Content headers placed into invalidHeaders?
return ResponseMessage(message);
}
答案 0 :(得分:1)
ZipArchive
完成工作后,流的位置将位于流的末尾。
在将此类流作为响应发送之前,请确保将流位置设置为0,如下所示:
memoryStream.Position = 0;