有个需求就是,附件中的文件(比如 txt\excel\jpg…)一个个下载有些麻烦,想实现打包下载功能,比如网易邮箱的打包下载,于是就有了此文。
借助外力
引入ICSharpCode.SharpZipLib.dll
引入命名空间
1 2
| using ICSharpCode.SharpZipLib.Zip; using System.IO;
|
核心代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| namespace NoneLibrary { public class BatchDownload { public byte[] Download(string[] path) { byte[] buffer = null; using(MemoryStream ms = new MemoryStream()) { using(ZipFile zip = ZipFile.Create(ms)) {
zip.BeginUpdate(); zip.NameTranform = new MyNameTranform();
if(path.Length == 0) throw new Exception("参数path路径为空!!");
foreach(var p in path) { zip.Add(p); } zip.CommitUpdate();
buffer = new byte[ms.Length]; ms.Posotion = 0; ms.Read(buffer, 0, buffer.Length);
}
}
return buffer;
}
} public class MyNameTranform : ICSharpCode.SharpZipLib.Core.INameTransform { public string TransformDirectory(string name) { return null; } public string TransformFile(string name) { return Path.GetFileName(name); } }
}
|
输出
1 2 3 4 5 6 7
| Response.Clear(); Response.Charset = "GB2312"; Response.ContentEncoding = System.Text.Encoding.UTF8; Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip"); Response.BinaryWrite(buffer); Response.Flush(); Response.End();
|