.Net Core实现下载多个文件并压缩打包

一、本示例使用环境:Net Core3.1、WebAPI、IIS

二、使用核心类:ZipFile

三、示例代码(亲测有效)

using System.Net.Http;
using System.IO.Compression;

对线上文件进行打包压缩:

 public async Task<ApiResponse<string>> DownFile()
        {
            //自定义的返回结果类
            ApiResponse<string> result = new ApiResponse<string>();
            try
            {
                //远程下载多个文件的地址
                List<string> filePaths = new List<string>() { 
                    "http://model.netai.vip/myupfiles/u4f/201029115909/cover-fece024a-af02-4e75-b78b-ce6b0b2c697f.jpg",
                    "http://model.netai.vip/myupfiles/u4f/201029115909/obj-d7074dca-cead-4bd0-965a-fc60b02db5ce.obj",
                    "http://model.netai.vip/myupfiles/u4f/201029115909/material-3ac7911f-64c0-4765-bf0f-26c0972023aa.mtl",
                    "http://model.netai.vip/myupfiles/u4f/201029115909/handpaint-118835d2-6286-49b5-9cc3-b7e123a41bbd.aim" };

                //多个文件的重命名
                List<string> fileNames = new List<string>() { "cover.jpg", "obj.obj", "material.mtl", "handpaint.aim" };

                //先判断是否保存有上次打包的压缩文件
                if (System.IO.File.Exists(Directory.GetCurrentDirectory() + "/wwwroot/ziliao.zip"))
                {
                    System.IO.File.Delete(Directory.GetCurrentDirectory() + "/wwwroot/ziliao.zip");
                }
                //准备用来存放下载的多个文件流目录
                string pathZip = Directory.GetCurrentDirectory() + "/wwwroot/downfile/";
                for (int i = 0; i < filePaths.Count; i++)
                {
                    string newPath = pathZip + "dir"+i;
                    if (!Directory.Exists(newPath))
                    {
                        Directory.CreateDirectory(newPath);
                    }
                    string path = filePaths[i];
                    HttpClient client = new HttpClient();
                    client.BaseAddress = new Uri(path);
                    //根据文件信息中的文件地址获取远程服务器,返回文件流
                    var stream = await client.GetStreamAsync(path);

                    var fils = File(stream, "application/vnd.android.package-archive", Path.GetFileName(path));
                    //创建文件流(文件路径,文件操作.创建)
                    using (FileStream fs = new FileStream(newPath + "/" + fileNames[i], FileMode.Create))
                    {
                        //复制文件流
                        fils.FileStream.CopyTo(fs);
                    }
                }
                //对多个文件流所在的目录进行压缩
                ZipFile.CreateFromDirectory(Directory.GetCurrentDirectory() + "/wwwroot/downfile/", Directory.GetCurrentDirectory() + "/wwwroot/" + "ziliao.zip");
                //删除目录以及目录下的子文件
                //存在即删除
                if (Directory.Exists(pathZip))
                {
                    Directory.Delete(pathZip, true);
                }
                //result.code = flag ? StatusCodes.Status200OK : StatusCodes.Status417ExpectationFailed;
                result.message = "压缩成功";
            }
            catch (Exception ex)
            {
                result.message = "上传异常,原因:" + ex.Message;
            }
            return result;
        }

对本地文件进行打包压缩

/// <summary>
        /// 多文件打包压缩
        /// </summary>
        /// <param name="folderPath">需要打包的文件夹</param>
        /// <param name="zipName">zip文件名</param>
        /// <returns></returns>
        private string PackFiles(string folderPath, string zipName)
        {
            string webRootPath = _hostingEnvironment.WebRootPath;

            //导出所存文件夹
            string folder_download = ConfigurationHelper.GetSingleNode("Emporary_Zip_Folder");

            //虚拟目录
            string appUrl = ConfigurationHelper.GetSingleNode("File_AppUrl");

            #region 打包压缩

            //生成导出所存文件夹
            var zip_download = Path.Combine(webRootPath, folder_download);
            if (!System.IO.Directory.Exists(zip_download))
            {
                System.IO.Directory.CreateDirectory(zip_download);
            }
            var zipPath = Path.Combine(webRootPath, zip_download, zipName);

            //CreateFromDirectory(待打包文件夹地址,打包后完整地址),
            ZipFile.CreateFromDirectory(folderPath, zipPath);

            //删除打包目录以及目录下的子文件(存在即删除)
            if (Directory.Exists(folderPath))
            {
                Directory.Delete(folderPath, true);
            }

            #endregion

            //线上下载地址
            var downloadZipPath = $"{Request.Host}/" + appUrl + $"/{folder_download}/{zipName}";
            return downloadZipPath;
        }

 

posted @ 2021-11-30 17:40  潇潇mini  阅读(1565)  评论(1编辑  收藏  举报