sha*_*urg 3 c# ziparchive asp.net-core asp.net-core-webapi
问题是如何使用 ASP.NET Core 2(当前)Web API 动态创建压缩(压缩)文件夹?
我在用 System.IO.Compression.ZipArchive
我已经有几篇博客文章使用流或字节数组来完成,所有这些都给了我相同的输出。
我可以下载 zip 文件夹,但无法打开它。
压缩后的文件夹大小正确。虽然打不开。
我希望它工作的方式是让用户单击运行此操作的按钮并返回一个包含一个或多个文件的压缩文件夹。
[HttpGet]
[Route("/api/download/zip")]
public async Task<IActionResult> Zip()
{
byte[] bytes = null;
using (MemoryStream zipStream = new MemoryStream())
using (var zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
{
var tempFileName = await _azure.GetFilesByRef("Azure_FilePath");
// Running just this line gives me the zipped folder (empty) which I can open
ZipArchiveEntry entry = zip.CreateEntry("File1.pdf", CompressionLevel.Fastest);
// Adding this 2nd section will download the zip but will not open the zip folder
using (Stream stream = entry.Open())
using (FileStream fs = new FileStream(tempFileName, FileMode.Open, FileAccess.Read))
{
await fs.CopyToAsync(stream);
}
bytes = zipStream.ToArray();
}
return File(bytes, MediaTypeNames.Application.Zip, $"Attachments{DateTime.Now.ToBinary()}.zip");
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以发现错误或提出替代解决方案吗?
在处理存档之前,所有数据都不会写入流。因此,在这种情况下,如果存档尚未刷新,流中的数据可能不完整。
memoryStream.ToArray 在存档有机会将其所有数据刷新到底层流之前被调用。
考虑重构为
//...
var tempFileName = await _azure.GetFilesByRef("Azure_FilePath");
using (MemoryStream zipStream = new MemoryStream()) {
using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Create, leaveOpen: true)) {
ZipArchiveEntry entry = archive.CreateEntry("File1.pdf", CompressionLevel.Fastest);
using (Stream stream = entry.Open())
using (FileStream fs = new FileStream(tempFileName, FileMode.Open, FileAccess.Read)) {
await fs.CopyToAsync(stream);
}
}// disposal of archive will force data to be written to memory stream.
zipStream.Position = 0; //reset memory stream position.
bytes = zipStream.ToArray(); //get all flushed data
}
//...
Run Code Online (Sandbox Code Playgroud)
您的示例中还假设FileStream打开的是所创建条目的正确文件类型;单个PDF文件。否则考虑从tempFileName.
您必须为要添加到存档中的每个项目添加唯一条目(文件路径)。