在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
直接上代码供大家参考。。。 前端页面就是一个下载的Button。。 <body> <form id="form1" runat="server"> <div> <asp:button ID="btn_down" runat="server" text="下载" onclick="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); } } } } 压缩的代码的没看懂的话,可以参考我的文章: |
请发表评论