ASP.NET Download All Files as Zip

后端 未结 4 426
不知归路
不知归路 2020-12-14 12:31

I have a folder on my web server that has hundreds of mp3 files in it. I would like to provide the option for a user to download a zipped archive of every mp3 in the directo

相关标签:
4条回答
  • 2020-12-14 13:12
                foreach (GridViewRow gvrow in grdUSPS.Rows)
                {
                      CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
                    if (chk.Checked)
                    {
                    string fileName = gvrow.Cells[1].Text;
    
                    string filePath = Server.MapPathfilename);
                    zip.AddFile(filePath, "files");
                    }
                }
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=DownloadedFile.zip");
                Response.ContentType = "application/zip";
                zip.Save(Response.OutputStream);
                Response.End();
    
    0 讨论(0)
  • 2020-12-14 13:20

    Here is code I use to do this with DotNetZip - works very well. Obviously you will need to provide the variables for outputFileName, folderName, and includeSubFolders.

    response.ContentType = "application/zip";
    response.AddHeader("content-disposition", "attachment; filename=" + outputFileName);
    using (ZipFile zipfile = new ZipFile()) {
      zipfile.AddSelectedFiles("*.*", folderName, includeSubFolders);
      zipfile.Save(response.OutputStream);
    }
    
    0 讨论(0)
  • 2020-12-14 13:26

    I can't believe how easy this was. After reading this, here is the code that I used:

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Clear();
        Response.BufferOutput = false;
        Response.ContentType = "application/zip";
        Response.AddHeader("content-disposition", "attachment; filename=pauls_chapel_audio.zip");
    
        using (ZipFile zip = new ZipFile())
        {
            zip.CompressionLevel = CompressionLevel.None;
            zip.AddSelectedFiles("*.mp3", Server.MapPath("~/content/audio/"), "", false);
            zip.Save(Response.OutputStream);
        }
    
        Response.Close();
    }
    
    0 讨论(0)
  • 2020-12-14 13:26

    You could add a custom handler (.ashx file) that takes the file path, reads the file compresses it using a compression library and returns the bytes to the end user with the correct content-type.

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