使用SharpZipLib通过.net中的http流式传输zip文件

And*_*asN 12 asp.net zip http stream

我正在制作一个简单的下载服务,以便用户可以从外部网站下载他的所有图像.要做到这一点,我只需将所有内容压缩到http流.

然而,似乎一切都存储在内存中,并且直到zip文件完成并且输出关闭才发送数据.我希望服务立即开始发送,而不是使用太多内存.

public void ProcessRequest(HttpContext context)
{
    List<string> fileNames = GetFileNames();
    context.Response.ContentType = "application/x-zip-compressed";
    context.Response.AppendHeader("content-disposition", "attachment; filename=files.zip");
    context.Response.ContentEncoding = Encoding.Default;
    context.Response.Charset = "";

    byte[] buffer = new byte[1024 * 8];

    using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutput = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(context.Response.OutputStream))
    {
        foreach (string fileName in fileNames)
        {
            ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);
            zipOutput.PutNextEntry(zipEntry);
            using (var fread = System.IO.File.OpenRead(fileName))
            {
                ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(fread, zipOutput, buffer);
            }
        }
        zipOutput.Finish();
    }

    context.Response.Flush();
    context.Response.End();
}
Run Code Online (Sandbox Code Playgroud)

我可以看到工作进程内存在生成文件时增长,然后在完成发送时释放内存.如何在不使用太多内存的情况下执行此操作?

Jon*_*eet 11

禁用响应缓冲,context.Response.BufferOutput = false;Flush从代码末尾删除调用.