MVC实现实现文件流打包成压缩包
MVC實現實現文件流打包成壓縮包
1、使用壓縮類庫SharpZipLib?
SharpZipLib 是一款比較經典實用C#壓縮類庫
SharpZipLib 庫特點:功能豐富、穩定 ,支持主流 zip、Gzip Tar BZip2 格式
2、項目中引用
SharpZipLib的官方地址是:http://icsharpcode.github.io/SharpZipLib/,實際使用可以通過NuGet獲取,在NuGet的地址是:http://www.nuget.org/packages/SharpZipLib/
在Visual Studio中可以通過NuGet程序包管理控制臺輸入命令PM> Install-Package SharpZipLib或者用NuGet管理界面搜索并安裝。
需要引用命名空間:
?using ICSharpCode.SharpZipLib.Checksums;?
?using ICSharpCode.SharpZipLib.Zip;?
?using System.IO;
3、MVC代碼示例 直接從文件流輸出zip
//控制器寫法
public FileResult PrintData()
{
? ? ? ? ? ? byte[] bytePDF = 需要打包的文件流;
? ? ? ? ? ? byte[] result = null;
? ? ? ? ? ? using (MemoryStream ms = new MemoryStream())
? ? ? ? ? ? {
? ? ? ? ? ? ? ? using (ZipOutputStream zipStream = new ZipOutputStream(ms))
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? zipStream.Password = "123456";//設置壓縮包密碼
? ? ? ? ? ? ? ? ? ? ZipEntry entry = new ZipEntry("文件名");
? ? ? ? ? ? ? ? ? ? entry.DateTime = DateTime.Now;//創建時間
? ? ? ? ? ? ? ? ? ? zipStream.PutNextEntry(entry);
? ? ? ? ? ? ? ? ? ? zipStream.Write(bytePDF, 0, bytePDF.Length);
? ? ? ? ? ? ? ? ? ? zipStream.CloseEntry();
? ? ? ? ? ? ? ? ? ? zipStream.IsStreamOwner = false;
? ? ? ? ? ? ? ? ? ? zipStream.Finish();
? ? ? ? ? ? ? ? ? ? zipStream.Close();
? ? ? ? ? ? ? ? ? ? ms.Position = 0;
? ? ? ? ? ? ? ? ? ? //壓縮后的數據被保存到了byte[]數組中。
? ? ? ? ? ? ? ? ? ? result = ms.ToArray();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
return File(result, "application/zip", "文件名.zip");
}
總結
以上是生活随笔為你收集整理的MVC实现实现文件流打包成压缩包的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CSS 相对|绝对(relative/a
- 下一篇: 动软代码生成器的具体使用方法步骤