将 ZipArchive 与 ASP.NET Core Web Api 结合使用

问题是如何使用 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");

}

任何人都可以发现错误或提出替代解决方案吗?


喵喔喔
浏览 274回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP