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

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

二、使用核心类:ZipFile

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

using System.Net.Http;
using System.IO.Compression;
复制代码
[HttpGet,Route("DownFile")]
        [Authorize]
        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;
        }
复制代码

注意:示例中的多个文件下载地址已不可用,需要替换成你们自己的文件所在地址

压缩完成后,可前往项目下的/wwwroot/downfile/目录查看压缩好的ziliao.zip文件,并且压缩文件的目录结构可以随自己的实际情况进行改动

本文为我自己原创,转载请注明出处,谢谢~

posted @   月井石  阅读(4364)  评论(2编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2013-11-27 input与button按钮背景图失效不显示的解决办法
点击右上角即可分享
微信分享提示