Streaming a zip file over http in .net with SharpZipLib

后端 未结 3 1846
我寻月下人不归
我寻月下人不归 2020-12-31 09:56

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.

However it seems ever

相关标签:
3条回答
  • 2020-12-31 10:44

    use Response.BufferOutput = false; at start of ProcessRequest and flush response after each file.

    0 讨论(0)
  • 2020-12-31 10:46

    FYI. This is working code to recursively add an entire tree of files, with streaming to browser:

    string path = @"c:\files";
    
    Response.Clear();
    Response.ContentType = "application/zip";
    Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", "hive.zip"));
    Response.BufferOutput = false;
    
    byte[] buffer = new byte[1024 * 1024];
    using (ZipOutputStream zo = new ZipOutputStream(Response.OutputStream, 1024 * 1024)) {
        zo.SetLevel(0);
        DirectoryInfo di = new DirectoryInfo(path);
        foreach (string file in Directory.GetFiles(di.FullName, "*.*", SearchOption.AllDirectories)) {
            string folder = Path.GetDirectoryName(file);
            if (folder.Length > di.FullName.Length) {
                folder = folder.Substring(di.FullName.Length).Trim('\\') + @"\";
            } else {
                folder = string.Empty;
            }
            zo.PutNextEntry(new ZipEntry(folder + Path.GetFileName(file)));
            using (FileStream fs = File.OpenRead(file)) {
                ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(fs, zo, buffer);
            }
            zo.Flush();
            Response.Flush();
        }
        zo.Finish();
    }
    
    Response.Flush();
    
    0 讨论(0)
  • 2020-12-31 11:00

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

    0 讨论(0)
提交回复
热议问题