今天做项目中遇见一个压缩问题,我的目录结构是树形菜单,文件在服务器存储是平面存储,没有目录结构,所以在下载指定目录的时候要构建目录结构,如下:
当我右键点击下载b目录文件夹的时候要Download b 目录下的所有文件,并且有目录结构,实现如下:
public static void CreateZip(List<string> directories, List<string> filenames, string zipFileName, string dir)
{
using (ZipOutputStream ZipStream = new ZipOutputStream(System.IO.File.Create(dir + zipFileName)))
{
ZipStream.SetLevel();
ZipEntryFactory factory = new ZipEntryFactory();
foreach (var directory in directories)
{
string virtualDirectory = directory;
ZipEntry zipEntry = factory.MakeDirectoryEntry(virtualDirectory);
zipEntry.DateTime = DateTime.Now;
ZipStream.PutNextEntry(zipEntry);
} byte[] buffer = new byte[];
for (int i = ; i < filenames.Count; i++)
{
string file = filenames[i];
string newfileName = file.Replace(dir, string.Empty);
ZipEntry entry = factory.MakeFileEntry(directories[i] + "//" + newfileName); entry.DateTime = DateTime.Now;
ZipStream.PutNextEntry(entry); using (FileStream fs = System.IO.File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, , buffer.Length);
ZipStream.Write(buffer, , sourceBytes);
} while (sourceBytes > );
}
}
ZipStream.Finish();
ZipStream.Close();
} System.Web.HttpContext.Current.Response.ContentType = "application/x-compress zip";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + zipFileName);
System.Web.HttpContext.Current.Response.TransmitFile(dir + zipFileName);
}
以下载b目录为例,参数如下:
directories:
filenames:
zipFileName:
dir:
调用上面方法传入正确参数即可生成正确的目录