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); }
//判断如果是火狐浏览器则不进行UTF-8编码
System.Web.HttpBrowserCapabilities browser = Request.Browser;
if (browser.Browser=="Firefox")
{
Response.AddHeader("content-disposition", "attachment;filename=" + saveName + ".zip");
}
else{
//IE和其它浏览器都要进行UTF-8编码,中文不编码会出现乱码
Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(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 组件,并添加引用