C#边压缩边下载

C#实现边压缩边下载,原理大概就是,每压缩一个文件就输出给浏览器。实现压缩与下载同步进行。

string zipName = "name.zip";  //压缩包名称
//洗干净开始办事
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename="+zipName);
HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
HttpContext.Current.Response.ContentType = "application/octet-stream";
//Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");

ZipOutputStream u = new ZipOutputStream(hc.Response.OutputStream);//压缩包文件流,用于对外输出
u.SetLevel(0);//压缩等级(越大压缩比越大,越耗时间)
u.SetComment("我是压缩包说明");//压缩包说明


ZipEntry z = null;
string[] fileArr = fileArr;//文件列表数组
for (int i = 0; i < fileArr.Length - 1; i++)
{
    if (fileArr[i] != "")  //分离出来的文件名不为空
    {
        string filename = picArr[i];//文件名称
        //如果文件存在,此处使用的是阿里云的oss存储,文件不在服务器
        if (OssManager.fileSize(filePath + filename) != -1)
        {
            Stream f = OssManager.getObjectMemoryStream(filePath + filename);//读取文件流
            byte[] b = new byte[f.Length];
            f.Read(b, 0, b.Length);          //将文件流加入缓冲字节中
            z = new ZipEntry(filename);     //以文件名称命名一个压缩单元
            u.PutNextEntry(z);             //将文件放入压缩文件流容器,注意:z不包含网站根目录
            u.Write(b, 0, b.Length);      //写入字节
            f.Close();//关闭容器
            u.Flush();
            if (hc.Response.IsClientConnected) HttpContext.Current.Response.Flush();//如果客户端在线就继续传输
            else
            {
                u.Finish(); // 结束压缩
                u.Close();  //关闭压缩流
                u.Dispose();
                HttpContext.Current.Response.End();
                return;
            }
        }
    }
}
u.Finish(); // 结束压缩
u.Flush();
u.Close();  //关闭压缩流
u.Dispose();
HttpContext.Current.Response.End();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值