ASP.NET 下载所有文件为 Zip

9
我有一个文件夹放在我的网络服务器上,里面有数百个mp3文件。我希望在网页上提供一个选项,让用户下载该目录下所有mp3的压缩归档文件。
我想要在需要时通过编程方式压缩文件。考虑到zip文件会非常大,为了性能原因,我认为我需要在压缩时将zip文件发送到响应流中。
这种做法可行吗?我该如何实现?

1
一旦得到答案,请确保在将文件添加到ZIP文件时关闭压缩... MP3文件无法很好地压缩.... - user180326
1
当然,因为它们已经被压缩了。谢谢提醒。 - Ronnie Overby
4个回答

12

这是我使用DotNetZip完成此操作的代码 - 运行非常好。显然,您需要为outputFileName、folderName和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);
}

2
如果您不想在Zip存档中包含目录子树,只需使用方法重载zipfile.AddSelectedFiles("*.*", folderName, direcotryInZip, includeSubFolders); - marquito
1
@marquito事实上,我认为如果它使用了那个重载,被接受的答案会更好。 - stephen
1
嘿 Ray,我需要关于创建 zip 文件的一点小帮助。如果你能帮忙的话,请在这里告诉我。非常感谢 :) 谢谢 - Nad
1
你有什么问题? - Ray
2
这里的响应是什么?它说上下文中不存在响应。尝试使用WebResponse、HttpResponse,但都不起作用。 - MSIslam
我的代码位于 HttpHandler 中。'response' 来自传递给 ProcessRequest 的 HttpContext。 - Ray

8

我简直不敢相信这有多么容易。在阅读这个之后,这是我使用的代码:

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

1
ZipFile zip = new ZipFile(),当我尝试创建时,它显示“您无法创建静态类ZipFile的实例”。我不知道为什么。 - Bimal Das
3
这是因为我回答中的ZipFile类来自DotNetZip库,而你的项目正在引用“System.IO.Compression.ZipFile”。 - Ronnie Overby

2
您可以添加一个自定义处理程序 (.ashx 文件),该处理程序接收文件路径,使用压缩库对文件进行压缩,并以正确的内容类型将字节返回给最终用户。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接