Asp.net MVC 生成zip并下载

前面有生成Excel或Word的示例,所以就不再重新写了。

这里只提供将指定文件以ZIP的方式下载。

创建一个 Zip工具类

public class ZIPCompressUtil
{
public static byte[] Zip(List<string> AllFilesPath)
{
try
{
if (AllFilesPath.Count > )
{
MemoryStream ms = new MemoryStream();
byte[] buffer = null; using (ZipFile file = ZipFile.Create(ms))
{
file.BeginUpdate();
file.NameTransform = new MyNameTransfom();
//通过这个名称格式化器,可以将里面的文件名进行一些处理。默认情况下,会自动根据文件的路径在zip中创建有关的文件夹。 for (int i = ; i < AllFilesPath.Count; i++)
{
string strFile = AllFilesPath[i];
file.Add(strFile);
} file.CommitUpdate(); buffer = new byte[ms.Length];
ms.Position = ;
ms.Read(buffer, , buffer.Length);
}
return buffer; }
return null;
}
catch
{
return null;
} }
}

在ActionResulit中调用Zip工具类。

public ActionResult ExportZIP()
{
List<string> fileAll = new List<string>();
//将所有文件所在的地址添加到fileAll中
...操作代码 //调用ZIP工具类,将集合传递给它
var buffer = ZIPCompressUtil.Zip(fileAll); Response.AppendHeader("content-disposition", "attachment;filename=名称.zip");
Response.BinaryWrite(buffer);
Response.Flush();
Response.End();
}

如果大家有什么好的想法,可以留言,我肯定会学习并实践好再拿出来分享。

非常感谢。

如果对您有帮助,请点赞!

上一篇:(路-莫)-Python基础一


下一篇:C++ GUI Qt4学习笔记01