.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;
        }

 


免責聲明!

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



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