ASP.NET将所有文件下载为Zip
我的网络服务器上有一个文件夹,里面有数百个mp3文件。 我想为用户提供从网页下载目录中每个mp3的压缩存档的选项。
我想只在需要时以编程方式压缩文件。 因为zip文件会非常大,所以我认为出于性能原因,我需要将zip文件发送到响应流, 因为它正在压缩 。
这可能吗? 我该怎么做?
以下是我使用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); }
我简直不敢相信这是多么容易。 阅读本文后 ,这里是我使用的代码:
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(); }
您可以添加一个采用文件路径的自定义处理程序(.ashx文件),读取文件使用压缩库对其进行压缩,并使用正确的内容类型将字节返回给最终用户。
上述就是C#学习教程:ASP.NET将所有文件下载为Zip分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
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();
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/991169.html