简体   繁体   English

流zip文件MVC.NET开始流式传输

[英]Stream zip file MVC.NET start streaming

I'm trying to create a method which continually streams a zip file as a user downloads it (so that there is no wasted streaming) 我正在尝试创建一种方法,在用户下载时不断传输zip文件(这样就不会浪费流媒体)

I added a thread.sleep to simulate latency 我添加了一个thread.sleep来模拟延迟

public override void ExecuteResult(ControllerContext context) {
    HttpResponseBase response = context.HttpContext.Response;

    response.Clear();
    response.ClearContent();
    response.ClearHeaders();
    response.Cookies.Clear();
    response.ContentType = ContentType;
    response.ContentEncoding = Encoding.Default;
    response.AddHeader("Content-Type", ContentType);
    context.HttpContext.Response.AddHeader("Content-Disposition", 
                            String.Format("attachment; filename={0}", 
                            this.DownloadName));
    int ind = 0;
    using (ZipOutputStream zipOStream = 
                new ZipOutputStream(context.HttpContext.Response.OutputStream))
    {
        foreach (var file in FilesToZip)
        {
            ZipEntry entry = new ZipEntry(FilesToZipNames[ind++]);
            zipOStream.PutNextEntry(entry);
            Thread.Sleep(1000);
            zipOStream.Write(file, 0, file.Length);
            zipOStream.Flush();
        }
        zipOStream.Finish();
    }    
    response.OutputStream.Flush();
}

It seems like the zip will not start streaming until all the files are files are zipped. 看起来拉链将不会开始流式传输,直到所有文件都是压缩文件。 Is there a way to stream continuously? 有没有办法连续流? Maybe with a different library? 也许有一个不同的图书馆?

Assuming the zip format is partial to streaming, your problem is that your response is being buffered by default. 假设zip格式部分流式传输,则问题是默认情况下您的响应正在缓冲。 If you set HttpResponseBase.BufferOutput to false, it should start streaming immediately. 如果将HttpResponseBase.BufferOutput设置为false,则应立即开始流式传输。

I think you might need to be flushing the outputstream rather than the zipostream to see any output to http. 我想你可能需要刷新输出流而不是zipostream来查看http的任何输出。 So response.OutputStream.Flush() would appear in your loop in that case. 所以在这种情况下,response.OutputStream.Flush()会出现在你的循环中。 Not sure if it will actually solver your problem though. 不确定它是否真的可以解决你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM