ASP .NET MVC使用ZipFile打包下载

asp.net MVC 的下载方法

引用using Ionic.Zip;

  <tr>
                <td><a href="\Upload\Download">下载</a></td>
</tr>
View
 //下载zip文件
        public ActionResult Download()
        {
            int count = 0;
            string ProcessInstanceID = "1";
            if (!string.IsNullOrEmpty(ProcessInstanceID))
            {
                string path = Server.MapPath("~/省略/"); //需要压缩的照片
                string zipDownLoad = Server.MapPath("~/省略/");
                string filePath = zipDownLoad + "KPI_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".zip"; //保存文件路径+文件名称
                DataTable Dt = new DataTable();
                Dt.Columns.Add("FileName", System.Type.GetType("System.String"));
                Dt.Rows.Add(new object[] { " 图片.PNG" });

                using (ZipFile zip = new ZipFile(System.Text.Encoding.UTF8))
                {
                    if (Dt != null && Dt.Rows.Count > 0)
                    {
                        foreach (DataRow filedr in Dt.Rows)
                        {
                            if (filedr["FileName"] != DBNull.Value && filedr["FileName"] != null && !string.IsNullOrEmpty(filedr["FileName"].ToString()))
                            {
                                zip.AddFile(path + filedr["FileName"].ToString(), ""); //第二个参数是去除嵌套文件 
                            }
                        }
                    }
                    else
                    {
                        return Content("<script>alert('无数据');location.href='/SalesTake/SalesIndex'</script>");

                    }
                    zip.Save(filePath);
                    //下载
                    if (System.IO.File.Exists(filePath))
                    {
                        FileInfo file = new FileInfo(filePath);
                        Response.ContentEncoding = System.Text.Encoding.UTF8; //解决中文乱码
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name)); //解决中文文件名乱码    
                        Response.AddHeader("Content-length", file.Length.ToString());
                        Response.ContentType = "appliction/octet-stream";
                        Response.WriteFile(file.FullName);
                        Response.Flush();
                        Response.End();
                        count = 1;

                    }
                }
            }
            return View();
        }
Controller

 

posted @ 2020-08-07 16:03  Angel~  阅读(327)  评论(0编辑  收藏  举报