前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#多文件打包下载

C#多文件打包下载

作者头像
闻语博客
发布2021-01-21 17:28:24
1.2K0
发布2021-01-21 17:28:24
举报
文章被收录于专栏:闻语博客闻语博客

js代码

代码语言:javascript
复制
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;
    }
})

<hr>

ashx代码

代码语言:javascript
复制
//产品名称
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");
代码语言:javascript
复制
/// <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();
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021 年 01 月,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档