C#将文件压缩成一个文件流,供前端下载

  直接上代码供大家参考。。。

  前端页面就是一个下载的Button。。  

<body>
    <form id="form1" runat="server">
    <div>
    <asp:button ID="btn_down" runat="server" text="下载" οnclick="btn_down_Click" />
    </div>
    </form>
</body>

  后台代码:

  protected void btn_down_Click(object sender, EventArgs e)
        {
            var name = Server.MapPath("huage");
            //if (!Directory.Exists(name))
            //    throw new FileNotFoundException("")
            var zipName = "test";
            DownZip(name, zipName,9);             
        }
        private void DownZip(string dirname, string zipfile, int level = 6, string password = "")
        {
            MemoryStream ms = new MemoryStream();//支持存储区为内存的流
            ZipOutputStream zos = new ZipOutputStream(ms);
            if (password != "")
                zos.Password = password;

            zos.SetLevel(level);
            AddZipEntry(dirname, zos, dirname);          
            zos.Finish();
            zos.Close();          
            Response.Clear();
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlDecode(zipfile,System.Text.Encoding.UTF8) + ".zip");
            Response.BinaryWrite(ms.ToArray());
            ms.Close();
            Response.Flush();
            Response.End();
        }
        private void AddZipEntry(string strPath, ZipOutputStream zos, string baseDirName)
        {
            DirectoryInfo dir = new DirectoryInfo(strPath);
            foreach (FileSystemInfo item in dir.GetFileSystemInfos())
            {
                if ((item.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    AddZipEntry(item.FullName, zos, baseDirName);
                }
                else
                {
                    FileInfo f_item = (FileInfo)item;
                    using (FileStream fs = f_item.OpenRead())
                    {
                        byte[] buffer = new byte[(int)fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        ZipEntry entry = new ZipEntry(f_item.FullName.Replace(baseDirName, ""));
                        zos.PutNextEntry(entry);
                        zos.Write(buffer, 0, buffer.Length);
                    }
                }
            }
        }

压缩的代码的没看懂的话,可以参考我的文章:

C#使用ICSharpCode.SharpZipLib.dll进行文件的压缩与解压

转载于:https://www.cnblogs.com/huage-1234/p/8601600.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值