多个文件压缩下载

 protected void Button1_Click(object sender, EventArgs e)
        {
            //MemoryStream ms = new MemoryStream();
            //byte[] buffer = null;
            //using (ZipFile file = ZipFile.Create(ms))
            //{
            //    file.BeginUpdate();
            //  //  file.NameTransform = new MyNameTransfom();//通过这个名称格式化器,可以将里面的文件名进行一些处理。默认情况下,会自动根据文件的路径在zip中创建有关的文件夹。
            //    file.Add(HttpContext.Current.Server.MapPath("img/010.jpg"));
            //    file.Add(HttpContext.Current.Server.MapPath("img/020.jpg"));
            //    file.CommitUpdate();
            //    buffer = new byte[ms.Length];
            //    ms.Position = 0;
            //    ms.Read(buffer, 0, buffer.Length);
            //}
            //Response.AddHeader("content-disposition", "attachment;filename=test.zip");
            //Response.BinaryWrite(buffer);
            //Response.Flush();
            //Response.End();

            string path = "C:\\Attach\\ZX";                          //创建文件的路径
            List<string> filelist = new List<string>();
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string img1 = HttpContext.Current.Server.MapPath("img/010.jpg");
            string img2 = HttpContext.Current.Server.MapPath("img/020.jpg");
            File.Copy(img1, path+"\\"+"010.jpg");
            filelist.Add(path + "\\" + "010.jpg");              //将要下载的文件复制到新创建的文件中
            File.Copy(img2, path+"\\"+"020.jpg");
            filelist.Add(path + "\\" + "020.jpg");
            ZipDown(filelist, "", "论文");                          //将文件进行压缩下载
            if (Directory.Exists(path))
            {
               Directory.Delete(path, true);                    //删除新创建的文件
            }
           
        }
        public void ZipDown(List<string> fileToZips, string zipedFile, string zipfilename)
        {
            Response.Clear();
            Response.ContentType = "application/zip";
            Response.AddHeader("content-disposition", "filename=" + zipfilename + ".zip");
            Response.HeaderEncoding = System.Text.Encoding.Default;
            using (ZipFile zip = new ZipFile(System.Text.Encoding.Default))//解决中文乱码问题 
            {
                foreach (string fileToZip in fileToZips)
                {
                    zip.AddFile(fileToZip, "");
                }
                zip.Save(Response.OutputStream);
            }
            Response.End(); 
        }

猜你喜欢

转载自www.cnblogs.com/zxnew/p/9250563.html