首先引入ICSharpCode.SharpZipLib插件,下圖中的兩個都可以,只是版本不同(如果你有安裝過npoi,可能裏面默認會有第二個版本的插件,直接引用就好了),下面話不多說,上代碼
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Web.Mvc;
namespace WebApplication2.Controllers
{
public class ZipController : Controller
{
public void DownZip()
{
byte[] fileBytes= DownAllProductClause(new List<FileHelpInfo>());
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + "附件" + ".rar");
Response.AddHeader("Content-Length", fileBytes.Length.ToString());
Response.BinaryWrite(fileBytes);
Response.End();
Response.Close();
}
public byte[] DownAllProductClause(List<FileHelpInfo> urlArray)
{
//安全協議設置 一般情況下如果不是訪問https則不需要設置
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
System.Net.WebClient myWebClient = new System.Net.WebClient();
Dictionary<string, Stream> dc = new Dictionary<string, Stream>();
foreach (var item in urlArray)
{
byte[] data = myWebClient.DownloadData(item.FilePath);
Stream stream = new MemoryStream(data);
dc.Add(item.FileName, stream);
}
byte[] fileBytes = ConvertZipStream(dc);
return fileBytes;
}
public byte[] ConvertZipStream(Dictionary<string, Stream> streams)
{
byte[] buffer = new byte[6500];
MemoryStream returnStream = new MemoryStream();
var zipMs = new MemoryStream();
/*
* 解決中文亂碼問題
*
* ICSharpCode.SharpZipLib 0.86版本使用ZipConstants.DefaultCodePage
* ZipConstants.DefaultCodePage = Encoding.GetEncoding("gbk").CodePage;
*
* ICSharpCode.SharpZipLib 較新的版本使用ZipStrings.CodePage 我用的是1.2幾的版本
* ZipStrings.CodePage = Encoding.GetEncoding("gbk").CodePage;
*
* */
ZipStrings.CodePage = Encoding.GetEncoding("gbk").CodePage;
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));//fileName 如果不需要文件夾就寫文件名稱,如需多級目錄:文件夾/文件名稱
while (true)
{
var readCount = streamInput.Read(buffer, 0, buffer.Length);
if (readCount > 0)
{
zipStream.Write(buffer, 0, readCount);
}
else
{
break;
}
}
zipStream.Flush();
}
kv.Value.Close();
}
zipStream.Finish();
zipMs.Position = 0;
zipMs.CopyTo(returnStream, 5600);
}
returnStream.Position = 0;
byte[] returnBytes = new byte[returnStream.Length];
returnStream.Read(returnBytes, 0, returnBytes.Length);
returnStream.Seek(0, SeekOrigin.Begin);
return returnBytes;
}
}
public class FileHelpInfo
{
public string FilePath { get; set; }
public string FileName { get; set; }
}
}