C#/.Net文件打包下载
Dictionary<string, Stream> streams = new Dictionary<string, Stream> (); Stream streamWriter = null; //将所有文件流在循环中加进,根据自己情况来写
streamWriter = File.Open(filePath, FileMode.Open);
streams.Add(strName, streamWriter);
//下面可以直接复制粘贴 MemoryStream ms = new MemoryStream(); ms = PackageManyZip(streams); byte[] bytes = new byte[(int)ms.Length]; ms.Read(bytes, 0, bytes.Length); ms.Close(); Response.ContentType = "application/octet-stream"; //通知浏览器下载文件而不是打开 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("打包文档.zip", System.Text.Encoding.UTF8)); Response.BinaryWrite(bytes); Response.Flush();
/// <summary> /// 将多个流进行zip压缩,返回压缩后的流 /// </summary> /// <param name="streams">key:文件名;value:文件名对应的要压缩的流</param> /// <returns>压缩后的流</returns> static MemoryStream PackageManyZip(Dictionary<string, Stream> streams) { byte[] buffer = new byte[6500]; MemoryStream returnStream = new MemoryStream(); var zipMs = new MemoryStream(); using (ZipOutputStream zipStream = new ZipOutputStream(zipMs)) { zipStream.SetLevel(9); foreach (var kv in streams) { string fileName = kv.Key; using (var streamInput = kv.Value) { zipStream.PutNextEntry(new ZipEntry(fileName)); while (true) { var readCount = streamInput.Read(buffer, 0, buffer.Length); if (readCount > 0) { zipStream.Write(buffer, 0, readCount); } else { break; } } zipStream.Flush(); } } zipStream.Finish(); zipMs.Position = 0; zipMs.CopyTo(returnStream, 5600); } returnStream.Position = 0; return returnStream; }