编程语言
首页 > 编程语言> > C#多文件打包下载

C#多文件打包下载

作者:互联网

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();
        }
    }
}

 

标签:string,fileToZip,C#,ZipStream,buffer,打包,new,GoodsName,下载
来源: https://www.cnblogs.com/zpblogs/p/11833533.html