/// <summary> /// 下载文件 /// </summary> /// <param name="dt">需要处理的数据集</param> /// <param name="imgUrl">文件在数据库里的名称</param> /// <param name="zipFileName">导出的zip压缩包名称</param> public static void FileDownload(DataTable dt, string imgUrl, string zipFileName) { List<string> tmpStr = new List<string>(); if (dt.Rows.Count > 0) { tmpStr.AddRange(from DataRow dr in dt.Rows select dr[imgUrl].ToString()); } if (tmpStr.ToArray().Length > 0) { using (ZipOutputStream s = new ZipOutputStream(File.Create(HttpContext.Current.Server.MapPath("") + "\\uploaded\\" + zipFileName))) { s.SetLevel(1); //设置压缩等级,等级越高压缩效果越明显,但占用CPU也会更多 foreach (string t in tmpStr) { string fileName = HttpContext.Current.Server.MapPath("") + "/uploaded/req/" + t; using (FileStream fs = File.OpenRead(fileName)) { byte[] buffer = new byte[4 * 1024]; //缓冲区,每次操作大小 if (!string.IsNullOrEmpty(fileName)) { ZipEntry entry = new ZipEntry(Path.GetFileName(fileName)); s.PutNextEntry(entry); int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); //读取文件内容(1次读4M,写4M) s.Write(buffer, 0, sourceBytes); //将文件内容写入压缩相应的文件 } while (sourceBytes > 0); } } } s.CloseEntry(); } var fName = HttpContext.Current.Server.MapPath("") + "\\uploaded\\" + zipFileName; if (!string.IsNullOrEmpty(fName)) { FileInfo downloadFile = new FileInfo(fName); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.Buffer = true; zipFileName = HttpUtility.UrlEncode(zipFileName, Encoding.UTF8); HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + zipFileName); HttpContext.Current.Response.ContentType = "application/zip"; HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("shift-jis"); HttpContext.Current.Response.AppendHeader("Content-Length", downloadFile.Length.ToString()); HttpContext.Current.Response.WriteFile(fName); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.Close(); HttpContext.Current.Response.End(); } if (File.Exists(fName)) { File.Delete(fName); } } }
链接:https://pan.baidu.com/s/1q8j5GUzAWUG1DY0DgkgCgg 密码:b2ru