MVC实现实现文件流打包成压缩包

MVC实现实现文件流打包成压缩包


640?wx_fmt=jpeg


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");

}


原文地址:https://www.cnblogs.com/hgmyz/p/12351599.html