JS文件
var Arrurl = [{ "name": "盡職調查.pdf" }, { "name": "簡介.pdf" }, { "name": "信托合同.pdf" }]; //ajax調用ashx $.ajax({ type: 'post', url: "../DownZip.ashx", data: { url: JSON.stringify(Arrurl), //需打包文件的文件名拼接json數組 GoodsName: "打包好", //打包后的壓縮包名稱 }, success: function (ret) { //執行返回壓縮包路徑下載 window.location.href = ret; } })
ashx文件
//產品名稱 string GoodsName = context.Request["GoodsName"]; //JSON數組文件路徑 var itemJson = new JavaScriptSerializer().Deserialize<List<Dictionary<string, string>>>(context.Request["url"].ToString()); //List集合 foreach循環添加路徑 List<string> listFile = new List<string>(); foreach (var item in itemJson) { listFile.Add(@"D:\atmoney\files\UserPic\" + item["name"].ToString() + ""); } //壓縮包保存路徑 string downzipurl = @"D:\atmoney\files\GoodsDownLoad\" + GoodsName + ".zip"; //執行打包 ZipFile(listFile, downzipurl, 0); //返回文件路徑 context.Response.Write(@"http://www.xx.cn/files/GoodsDownLoad/" + GoodsName + ".zip");
/// <summary> /// 壓縮duo個文件 /// </summary> /// <param name="fileToZip">要進行壓縮的文件名</param> /// <param name="zipedFile">壓縮后生成的壓縮文件名</param> public static void ZipFile(List<string> fileToZipS, string zipedFile, int Level) { foreach (string fileToZip in fileToZipS) { //如果文件沒有找到,則報錯 if (!File.Exists(fileToZip)) { throw new System.IO.FileNotFoundException("指定要壓縮的文件: " +fileToZip+ " 不存在!"); break; } } using (FileStream ZipFile = File.Create(zipedFile)) { using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile)) { foreach (string fileToZip in fileToZipS) { string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\")); using (FileStream fs = File.OpenRead(fileToZip)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); ZipEntry ZipEntry = new ZipEntry(fileName); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(Level); ZipStream.Write(buffer, 0, buffer.Length); } } ZipStream.Finish(); ZipStream.Close(); } } }
