基于Layui + .net mvc 文件压缩

html

<button type="button" class="layui-btn layui-btn-sm" onclick="compress()">文件压缩</button>

js

function compress() {
    $.post('/FileCompress/compress', {}, function () {});
}

Controller

using COMMON;
using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace SFMVC3._0.Controllers
{
    public class FileCompressController : Controller
    {
        /// <summary>
        /// 获取文件
        /// </summary>
        /// <returns></returns>
        public string getFiles()
        {
            List<string> NoiceList = new List<string>();

            NoiceList.Add(Server.MapPath(String.Format("/upload/{0}", "Photo")));//压缩文件的位置,Photo为文件的名字

            string downzipname = Guid.NewGuid().ToString() + ".zip";
            string downzipurl = Server.MapPath(String.Format("/upload/{0}", downzipname));//把压缩后文件夹放入的位置,在方法中自动创建downzipname为文件夹的名字
            FileCompressHelper.ZipFile(NoiceList, downzipurl, 0);
            return downzipname;
        }
    }
}
FileCompressHelper
using System.Collections.Generic;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace COMMON
{
    public class FileCompressHelper
    {
        /// <summary>
        /// 压缩文件的方法
        /// </summary>
        /// <param name="fileToZipS">传入的文件List</param>
        /// <param name="zipedFile">压缩文件夹的地址</param>
        /// <param name="Level">0</param>
        public static void ZipFile(List<string> fileToZipS, string zipedFile, int Level)
        {

            foreach (string fileToZip in fileToZipS)
            {
                //如果文件没有找到,则报错
                if (!File.Exists(fileToZip))
                {
                    throw new System.IO.FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
                    break;
                }
            }

            using (FileStream ZipFile = File.Create(zipedFile))
            {
                using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))
                {
                    foreach (string fileToZip in fileToZipS)
                    {
                        string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\"));

                        using (FileStream fs = File.OpenRead(fileToZip))
                        {
                            byte[] buffer = new byte[fs.Length];
                            fs.Read(buffer, 0, buffer.Length);
                            fs.Close();

                            ZipEntry ZipEntry = new ZipEntry(fileName);
                            ZipStream.PutNextEntry(ZipEntry);
                            ZipStream.SetLevel(Level);

                            ZipStream.Write(buffer, 0, buffer.Length);
                        }
                    }
                    ZipStream.Finish();
                    ZipStream.Close();
                }
            }
        }
    }
}

 

你可能感兴趣的