Asp.net MVC 生成zip並下載


前面有生成Excel或Word的示例,所以就不再重新寫了。

這里只提供將指定文件以ZIP的方式下載。

創建一個 Zip工具類 

public class ZIPCompressUtil
    {
        public static byte[] Zip(List<string> AllFilesPath)
        {
            try
            {
                if (AllFilesPath.Count > 0)
                {
                    MemoryStream ms = new MemoryStream();
                    byte[] buffer = null;

                    using (ZipFile file = ZipFile.Create(ms))
                    {
                        file.BeginUpdate();
                        file.NameTransform = new MyNameTransfom();
//通過這個名稱格式化器,可以將里面的文件名進行一些處理。默認情況下,會自動根據文件的路徑在zip中創建有關的文件夾。  

                        for (int i = 0; i < AllFilesPath.Count; i++)
                        {
                            string strFile = AllFilesPath[i];
                            file.Add(strFile);
                        }


                        file.CommitUpdate();

                        buffer = new byte[ms.Length];
                        ms.Position = 0;
                        ms.Read(buffer, 0, buffer.Length);
                    }
                    return buffer;
                   
                }
                return null;
            }
            catch
            {
                return null;
            }

        }
}
View Code

在ActionResulit中調用Zip工具類。

public ActionResult ExportZIP()
{
   List<string> fileAll = new List<string>();
   //將所有文件所在的地址添加到fileAll中
   ...操作代碼

   //調用ZIP工具類,將集合傳遞給它
   var buffer = ZIPCompressUtil.Zip(fileAll);

   Response.AppendHeader("content-disposition", "attachment;filename=名稱.zip");
   Response.BinaryWrite(buffer);
   Response.Flush();
   Response.End();
}    

 

如果大家有什么好的想法,可以留言,我肯定會學習並實踐好再拿出來分享。

非常感謝。

如果對您有幫助,請點贊!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM