我有一個文件列表與每個文件的複選框,如果用戶檢查許多文件,然後單擊下載我必須壓縮所有這些文件並下載它...就像郵件附件。 。下載多個文件作爲壓縮在.net
我已經使用的代碼中提到這post for single file download
請幫助如何下載多個文件,ZIP ..
我有一個文件列表與每個文件的複選框,如果用戶檢查許多文件,然後單擊下載我必須壓縮所有這些文件並下載它...就像郵件附件。 。下載多個文件作爲壓縮在.net
我已經使用的代碼中提到這post for single file download
請幫助如何下載多個文件,ZIP ..
您需要打包文件並將結果寫入響應。 您可以使用SharpZipLib壓縮庫。
代碼示例:
Response.AddHeader("Content-Disposition", "attachment; filename=" + compressedFileName + ".zip");
Response.ContentType = "application/zip";
using (var zipStream = new ZipOutputStream(Response.OutputStream))
{
foreach (string filePath in filePaths)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
var fileEntry = new ZipEntry(Path.GetFileName(filePath))
{
Size = fileBytes.Length
};
zipStream.PutNextEntry(fileEntry);
zipStream.Write(fileBytes, 0, fileBytes.Length);
}
zipStream.Flush();
zipStream.Close();
}
3個庫,我知道的是SharpZipLib(多功能格式),DotNetZip(一切ZIP)和ZipStorer(小型和緊湊型)。沒有鏈接,但他們都在codeplex上,並通過谷歌搜索。許可證和確切功能各不相同。
快樂編碼。
這是如何做到這一點的DotNetZip方式:DI擔保DotNetZip因爲我已經用它,它是迄今爲止C#最簡單的壓縮庫我遇到:)
檢查http://dotnetzip.codeplex.com/
http://dotnetzip.codeplex.com/wikipage?title=CS-Examples&referringTitle=Examples
在ASP.NET中創建可下載的zip。本示例在ASP.NET回發方法中動態創建zip文件,然後通過Response.OutputStream將該zip文件下載到請求的瀏覽器。沒有在磁盤上創建zip存檔。
public void btnGo_Click (Object sender, EventArgs e)
{
Response.Clear();
Response.BufferOutput= false; // for large files
String ReadmeText= "This is a zip file dynamically generated at " + System.DateTime.Now.ToString("G");
string filename = System.IO.Path.GetFileName(ListOfFiles.SelectedItem.Text) + ".zip";
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=" + filename);
using (ZipFile zip = new ZipFile())
{
zip.AddFile(ListOfFiles.SelectedItem.Text, "files");
zip.AddEntry("Readme.txt", "", ReadmeText);
zip.Save(Response.OutputStream);
}
Response.Close();
}
你好..感謝這個漂亮的回覆..但我想知道,我是否可以在添加到zip之前更改文件的名稱(在zip.AddFile命令之前)。我正在討論將要添加到ZIP中的文件,而不是zip文件的文件名。 – 2013-09-26 11:42:19
這太棒了......值得讚賞。你知道是否有任何實時的方法來知道壓縮的大小?我希望能夠告訴我的用戶如果壓縮,他們將下載的內容的大小。 – pearcewg 2011-10-06 22:46:00
@pearcewg,我認爲在這種情況下解決方案取決於您的要求。如果你知道什麼是檔案內容,你可以在頁面生成之前壓縮文件,並顯示檔案的大小。如果檔案內容可能有所不同,那麼這是一項非常重要的任務。我的想法是:1.將關於壓縮文件大小的信息放入數據庫中2.根據壓縮的統計數據顯示壓縮文件的近似大小。 – bniwredyc 2011-10-07 06:01:12
工作就像一個魅力。謝謝 – 2013-11-18 06:03:26