[英]ASP.NET Download All Files as 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文件),讀取文件使用壓縮庫對其進行壓縮,然后使用正確的內容類型將字節返回給最終用戶。
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.