zoukankan      html  css  js  c++  java
  • asp.net mvc 文件压缩下载

    压缩文件相关的类:

        public class ZIPCompressUtil
        {
            public static Tuple<bool, Stream> Zip(string strZipTopDirectoryPath, int intZipLevel, string strPassword, string[] filesOrDirectoriesPaths)
            {
                try
                {
                    List<string> AllFilesPath = new List<string>();
                    if (filesOrDirectoriesPaths.Length > 0) // get all files path
                    {
                        for (int i = 0; i < filesOrDirectoriesPaths.Length; i++)
                        {
                            if (File.Exists(filesOrDirectoriesPaths[i]))
                            {
                                AllFilesPath.Add(filesOrDirectoriesPaths[i]);
                            }
                            else if (Directory.Exists(filesOrDirectoriesPaths[i]))
                            {
                                GetDirectoryFiles(filesOrDirectoriesPaths[i], AllFilesPath);
                            }
                        }
                    }
    
                    if (AllFilesPath.Count > 0)
                    {
                        MemoryStream ms = new MemoryStream();
                        ZipOutputStream zipOutputStream = new ZipOutputStream(ms);
                        zipOutputStream.SetLevel(intZipLevel);
                        zipOutputStream.Password = strPassword;
    
                        for (int i = 0; i < AllFilesPath.Count; i++)
                        {
                            string strFile = AllFilesPath[i];
                            try
                            {
                                if (Directory.Exists(strFile)) //folder
                                {
                                    string strFileName = strFile.Replace(strZipTopDirectoryPath, "");
                                    if (strFileName.StartsWith(""))
                                    {
                                        strFileName = strFileName.Substring(0);
                                    }
                                    ZipEntry entry = new ZipEntry(strFileName + "/");
                                    entry.DateTime = DateTime.Now;
                                    zipOutputStream.PutNextEntry(entry);
                                }
                                else //file
                                {
                                    FileStream fs = File.OpenRead(strFile);
    
                                    byte[] buffer = new byte[fs.Length];
                                    fs.Read(buffer, 0, buffer.Length);
    
                                    string strFileName = strFile.Replace(strZipTopDirectoryPath, "");
                                    if (strFileName.StartsWith(""))
                                    {
                                        strFileName = strFileName.Substring(0);
                                    }
                                    ZipEntry entry = new ZipEntry(strFileName);
                                    entry.DateTime = DateTime.Now;
                                    zipOutputStream.PutNextEntry(entry);
                                    zipOutputStream.Write(buffer, 0, buffer.Length);
    
                                    fs.Close();
                                    fs.Dispose();
                                }
                            }
                            catch
                            {
                                continue;
                            }
                        }
    
                        zipOutputStream.Finish();
                        return new Tuple<bool, Stream>(true, ms);
                    }
                    else
                    {
                        return new Tuple<bool, Stream>(false, null);
                    }
                }
                catch
                {
                    return new Tuple<bool, Stream>(false, null);
                }
            }
    
            private static void GetDirectoryFiles(string strParentDirectoryPath, List<string> AllFilesPath)
            {
                string[] files = Directory.GetFiles(strParentDirectoryPath);
                for (int i = 0; i < files.Length; i++)
                {
                    AllFilesPath.Add(files[i]);
                }
                string[] directorys = Directory.GetDirectories(strParentDirectoryPath);
                for (int i = 0; i < directorys.Length; i++)
                {
                    GetDirectoryFiles(directorys[i], AllFilesPath);
                }
                if (files.Length == 0 && directorys.Length == 0) //empty folder
                {
                    AllFilesPath.Add(strParentDirectoryPath);
                }
            }
        }

    调用并提供下载的方法

            public ActionResult Export()
            {
                List<long> productIds = null;
                var url = Request.RawUrl;
                if (url.Contains("?"))
                {
                    string paramStr = url.Substring(url.LastIndexOf("?"));
                    string[] paramArray = paramStr.Split('&');
                    productIds = paramArray
                        .Select(item => item.Split('=').Length > 1 ? item.Split('=')[1] : "0")
                        .Select(value => value.TryLong(0)).ToList();
                }
    
                if (Directory.Exists(Server.MapPath("~/上架商品")))
                {
                    Directory.Delete(Server.MapPath("~/上架商品"), true);
                }
    
                var productlist = ProductOnSaleService.Instance.GetProductSkuImgsExportList(productIds);
                foreach (var productItem in productlist)
                {
                    var dir = Server.MapPath("~/上架商品/") + productItem.ProductId + "-" + productItem.LongName;
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    foreach (var skuItem in productItem.Skus)
                    { 
                        Bitmap rqBtimap = QrCodeHelper.Encode(BizKeyValService.Instance.Get(EnumBizKey.ProductShareUrl).BizVal
                            + "?id=" + productItem.ProductId + "&skuid=" + skuItem.SkuId, 430, 430);
                        rqBtimap.Save(dir + "/" + productItem.ProductId + "-" + skuItem.SkuId + "-" + skuItem.SkuName + ".jpg");
                        
                    }
                }
    
                var strZipTopDirectoryPath = Server.MapPath("~/");
                const int intZipLevel = 6;
                const string strPassword = "";
                var filesOrDirectoriesPaths = new string[] { Server.MapPath("~/上架商品") };
                var result = ZIPCompressUtil.Zip(strZipTopDirectoryPath, intZipLevel, strPassword, filesOrDirectoriesPaths);
                var buffer = new byte[result.Item2.Length];
                result.Item2.Position = 0;
                result.Item2.Read(buffer, 0, buffer.Length);
                result.Item2.Close();
                Response.AppendHeader("content-disposition", "attachment;filename=上架商品.zip");
                Response.BinaryWrite(buffer);
                Response.Flush();
                Response.End();
                return new EmptyResult();
            }

    js代码

    $("#btnExpress").click(function () {
            var selectedList = $.getSelectId(true);
            if (selectedList.length == 0) {
                $.alert("请选择商品");
                return;
            }
            var url = "/Product/ProductOnSale/Export";
            for (var i = 0; i < selectedList.length; i++) {
                url = (i == 0 ? url + "?param" + i + "=" + selectedList[i].toString() 
                    : url + "&param" + i + "=" + selectedList[i].toString());
            }
            location.href = url;
        });
  • 相关阅读:
    ASP.NET CORE 使用Consul实现服务治理与健康检查(2)——源码篇
    ASP.NET CORE 使用Consul实现服务治理与健康检查(1)——概念篇
    Asp.Net Core 单元测试正确姿势
    如何通过 Docker 部署 Logstash 同步 Mysql 数据库数据到 ElasticSearch
    Asp.Net Core2.2 源码阅读系列——控制台日志源码解析
    使用VS Code 开发.NET CORE 程序指南
    .NetCore下ES查询驱动 PlainElastic .Net 升级官方驱动 Elasticsearch .Net
    重新认识 async/await 语法糖
    EF添加
    EF修改部分字段
  • 原文地址:https://www.cnblogs.com/hellolong/p/4236275.html
Copyright © 2011-2022 走看看