在ASP Net Core中生成大的zip文件

时间:2019-03-04 10:16:16

标签: asp.net-mvc asp.net-core zip out-of-memory

我正在构建一个MVC控制器操作,该操作将构建一个包含两个文件的zip文件:

  • 一些从数据库序列化的元数据。
  • 相关内容文件实际上存储在天蓝色存储blob中

到目前为止,我的控制器可以正常工作,直到达到一定的文件大小为止。然后,当来自天蓝色的内容变得太大时,我肯定会遇到内存不足异常,这与我正在服务器内存中写入内容(不是无限的)有关。

所以现在我想知道应该采用哪种方法?在服务器上的临时路径中写入内容,或者还有其他选项吗?

这是我的控制者参考资料:

public async Task<ActionResult> Download(Guid? id)
    {

        if (id == null)
        {
            return NotFound();
        }

        var cIApplication = await _context.CIApplications
            .AsNoTracking()
            .SingleOrDefaultAsync(m => m.ID == id);
        if (cIApplication == null)
        {
            return NotFound();
        }

        //Serialize metadata : this will always be small
        byte[] metaData = BinSerializer.SerializeToByteArrayAsync<CIApplication>(cIApplication);

        //GetFile from Azure blob : This can reach several GB
        //StorageManagement is an helper class to manipulate Azure storage objects
        StorageManagement storage = new StorageManagement();
        byte[] content = await storage.GetBlobToStream("application", $"{cIApplication.ID}.zip");

        //Zip It and send it
        using (MemoryStream ms = new MemoryStream())
        {
            using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
            {
                var zipArchiveEntry = archive.CreateEntry($"{cIApplication.ID}.bin", CompressionLevel.Fastest);
                using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(metaData, 0, metaData.Length);

                zipArchiveEntry = archive.CreateEntry($"{cIApplication.ID}.zip", CompressionLevel.Fastest);
                using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(content, 0, content.Length);
            }
            return File(ms.ToArray(), "application/zip", $"{cIApplication.Publisher} {cIApplication.Name} {cIApplication.Version}.zip");
        }
    }

0 个答案:

没有答案