本文介绍了使用 SharpZipLib 在 .net 中通过 http 流式传输 zip 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm making a simple download service so a user can download all his images from out site.To do that i just zip everything to the http stream.

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

However it seems everything is stored in memory, and the data isn't sent til zip file is complete and the output closed.I want the service to start sending at once, and not use too much memory.

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();
}

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

I can see the the worker process memory growing while it makes the file, and then releases the memory when its done sending. How do i do this without using too much memory?

推荐答案

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

Disable response buffering with context.Response.BufferOutput = false; and remove the Flush call from the end of your code.

这篇关于使用 SharpZipLib 在 .net 中通过 http 流式传输 zip 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 16:41