问题是如何使用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");
}
有人能发现错误或提供另一种解决方案吗?