ASP.NET打包生成zip压缩文件
时间:2014-05-01 08:07:45
收藏:0
阅读:408
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using Microsoft.Win32; using System.Diagnostics; using ICSharpCode.SharpZipLib.Zip; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { } } protected void btnSave_Click(object sender, EventArgs e) { string str = "1.jpg|2.jpg|3.jpg";//文件名 string saveName = "test";//保存的文件名 MemoryStream ms = new MemoryStream(); byte[] buffer = null; using (ZipFile file = ZipFile.Create(ms)) { file.BeginUpdate(); file.NameTransform = new MyNameTransfom();//通过这个名称格式化器,可以将里面的文件名进行一些处理。默认情况下,会自动根据文件的路径在zip中创建有关的文件夹。 string[] s = str.Split(‘|‘); foreach (string item in s) { file.Add(Server.MapPath("~/newImages/" + item + "")); } file.CommitUpdate(); buffer = new byte[ms.Length]; ms.Position = 0; ms.Read(buffer, 0, buffer.Length); } Response.AddHeader("content-disposition", "attachment;filename=" + saveName + ".zip"); Response.BinaryWrite(buffer); Response.Flush(); Response.End(); } public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform { #region INameTransform 成员 public string TransformDirectory(string name) { return null; } public string TransformFile(string name) { return Path.GetFileName(name); } #endregion } }
注:需要下载一个 ICSharpCode.SharpZipLib.dll 组件,并添加引用
评论(0)