原理:1.将需要下载的文件保存到服务器上 (引用using ICSharpCode.SharpZipLib.Zip;)
EasyUIGridModel result = bll.Query(gridSetting.PageIndex, gridSetting.PageSize, AutoMapping.ConvertDto2Ht<BuyProView>(criteria), WorkContext.Identity, gridSetting.SortBy);
foreach (var date in (List<dynamic>)result.Rows)
{
//数据已二进制流保存在数据库中
if (date.BILLFILE != null)
{
string savepath = Server.MapPath("~/") + string.Format("DownloadPdf/发票{0}_{1}.pdf", date.NO, DateTime.Now.ToString("yyyyMMdd")); //文件位置
FileStream fs = new FileStream(savepath, FileMode.CreateNew);//将二进制写入内存保存
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(date.BILLFILE, 0, date.BILLFILE.Length); //保存文件
bw.Close();
fs.Close();
}
}
将文件打包到指定位置(服务器)
var filenames = Directory.GetFiles(Server.MapPath("~/DownloadPdf")); //需压缩的文件地址
var pdfpath =Server.MapPath("~/")+ string.Format("文档_{0}.zip", DateTime.Now.ToString("yyyyMMdd"));//打包文件地址
using (ZipOutputStream s = new ZipOutputStream(System.IO.File.Open(pdfpath, FileMode.OpenOrCreate)))
{
s.SetLevel(6); // 压缩级别 0-9
foreach (string file in filenames)
{
if (System.IO.File.Exists(file))
{
FileInfo item = new FileInfo(file);
FileStream fs = System.IO.File.OpenRead(item.FullName); //读取文件流
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length); //将文件读成2进制流
ZipEntry entry = new ZipEntry(item.Name);
s.PutNextEntry(entry); //将文件放入压缩流中
s.Write(buffer, 0, buffer.Length); //保存
fs.Close();
System.IO.File.Delete(file); //删除放入服务器的文件
}
}
}
FileStream fszip = new FileStream(pdfpath, FileMode.Open); //读取压缩文件
byte[] bytes = new byte[(int)fszip.Length]; //将压缩文件保存为2进制流
fszip.Read(bytes, 0, bytes.Length);
fszip.Close();
System.IO.File.Delete(pdfpath); //删除保存在服务器上的压缩文件
下载文件 (Response下载到客户端)
Response.Charset = “UTF-8”;
Response.ContentEncoding = System.Text.Encoding.GetEncoding(“UTF-8”);
Response.ContentType = “application/octet-stream”;
Response.AddHeader(“Content-Disposition”, “attachment; filename=” + Server.UrlEncode(string.Format(“文档_{0}.zip”, DateTime.Now.ToString(“yyyyMMdd”)))); //以流媒体形式下载
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();