Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream zip file MVC.NET start streaming

Tags:

c#

asp.net-mvc

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)

I added a thread.sleep to simulate latency

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?

like image 502
maxfridbe Avatar asked May 08 '09 05:05

maxfridbe


1 Answers

Assuming the zip format is partial to streaming, your problem is that your response is being buffered by default. If you set HttpResponseBase.BufferOutput to false, it should start streaming immediately.

like image 55
Richard Szalay Avatar answered Sep 30 '22 19:09

Richard Szalay