【问题标题】:.net core create on memory zipfile.net core 在内存 zipfile 上创建
【发布时间】:2019-04-22 00:59:03
【问题描述】:

我正在开发一个 MVC 项目,我在该项目中创建了动态的 pdf 文件 (wkhtmltopdf),我希望将其以 zip 文件的形式返回。 pdf 文件是即时生成的 - 我不需要存储它们,所以我返回 single 文件的代码是:

File(pdfBytes, "application/pdf", "file_name")

看看Microsoft docs他们的例子会遍历存储的文件:

 string startPath = @"c:\example\start";
 string zipPath = @"c:\example\result.zip";
 string extractPath = @"c:\example\extract";

 ZipFile.CreateFromDirectory(startPath, zipPath);
 ZipFile.ExtractToDirectory(zipPath, extractPath);

就我而言,我想创建 N 个 pdf 文件并将其作为 zip 文件返回到视图中。 比如:

ZipFile zip = new ZipFile();
foreach(var html in foundRawHTML)
{
//create pdf

//append pdf to zip
}

return zip;

虽然这是不可行的,因为:

  1. ZipFile 和 File 是静态的,不能实例化
  2. 无法即时将文件添加到 zip 中(在内存中)

欢迎任何帮助

【问题讨论】:

    标签: .net asp.net-core zip


    【解决方案1】:

    您可以在内存中使用字节数组和 System.IO.Compression 中的 ZipArchive,无需映射本地驱动器:

        public static byte[] GetZipArchive(List<InMemoryFile> files)
            {
                byte[] archiveFile;
                using (var archiveStream = new MemoryStream())
                {
                    using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create, true))
                    {
                        foreach (var file in files)
                        {
                            var zipArchiveEntry = archive.CreateEntry(file.FileName, CompressionLevel.Fastest);
                            using (var zipStream = zipArchiveEntry.Open())
                                zipStream.Write(file.Content, 0, file.Content.Length);
                        }
                    }
    
                    archiveFile = archiveStream.ToArray();
                }
    
                return archiveFile;
            }
    
    public class InMemoryFile
        {
            public string FileName { get; set; }
            public byte[] Content { get; set; }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-24
      • 1970-01-01
      • 2014-01-23
      • 2015-05-11
      • 1970-01-01
      • 2019-02-17
      • 1970-01-01
      相关资源
      最近更新 更多