C# .NET Core 批量下载文件

前段时间客户提了需求,要求批量下载文件,我的实现思路:

1.将文件下载到服务器的指定位置

2.打包压缩

3.下载

4.删除压缩包

考虑到如果压缩文件比较大,下载速度感人,所以用了异步,具体代码:

复制代码
        public async Task<IActionResult> GetSchoolEvidenceFiles(RongboRequest<FileQuery> request)
        {
            var url = "";
            var query = new RongboRequest<SchoolCollectionItemQuery>()
            {
                Data = new SchoolCollectionItemQuery()
            };

            var planId = this.GetCurrentPlan().Id;
            if (!string.IsNullOrWhiteSpace(request.Data.PlanningId)) {
                planId = request.Data.PlanningId;
            }
            var endIndexs = _indexService.GetByPlanIdAllIndex(planId).Data;
            if (!string.IsNullOrEmpty(request.Data.EndIndexId))
            {
                endIndexs = endIndexs.Where(p => p.Id == request.Data.EndIndexId).ToList();
            }
            if (request.Data.EndIndexs != null && request.Data.EndIndexs.Count() > 0)
            {
                endIndexs = endIndexs.Where(a => request.Data.EndIndexs.Contains(a.Id)).ToList();
            }
            var indexTypes = _typeService.GetAllBase().Data;
            var indicatorCollections = _indicatorCollectionBll.GetAllBase().Data;

            List<SchoolFileOutput1> schoolFileOutputList = new List<SchoolFileOutput1>();
            SchoolFileOutput1 schoolFileOutput = new SchoolFileOutput1();
            List<List<SchoolFileOutput1>> schoolFileOutputLists = new List<List<SchoolFileOutput1>>();

            var schools = _schoolService.GetDataByExpression(a => request.Data.SchoolList.Contains(a.Id) && a.SystemId == SystemIdInt).Data;
            //var files = _indexFileService.GetAllBase().Data;//获取佐证材料
            var files = _indexFileService.GetDataByExpression(a => request.Data.SchoolList.Contains(a.SchoolId)).Data;
            if (request.Data.EndIndexs != null && request.Data.EndIndexs.Count() > 0 )
            {
                files = files.Where(a => request.Data.EndIndexs.Contains(a.IndexId)).ToList();
            }
            List<List<ExpertiseIndexOutput>> TargetZzFiles = new List<List<ExpertiseIndexOutput>>();
            List<ExpertiseIndexOutput> expertiseIndexOutputList = new List<ExpertiseIndexOutput>();
            ExpertiseIndexOutput expertiseIndexOutput = new ExpertiseIndexOutput();
            foreach (var school in schools)
            {
                var schoolEndIndexs = endIndexs.Where(a => a.SchoolType.ToString() == school.SchoolType
                && (a.SchoolId == school.Id || a.SchoolId == "0")).ToList();
                expertiseIndexOutputList = new List<ExpertiseIndexOutput>();
                foreach (var endInex in schoolEndIndexs)
                {
                    expertiseIndexOutput = new ExpertiseIndexOutput();
                    var indextype = indexTypes.Where(a => a.Id == endInex.IndexType).FirstOrDefault()?.Type == 3 ? true : false;//判断是否监测指标
                    var indicatorCollection = indicatorCollections.Where(a => a.EndIndexId == endInex.Id).Where(a => a.IsSchoolWrite == 1).Any();//判断指标是否配置需要学校填报的采集项

                    var usefiles = files.Where(m => m.SchoolId == school.Id && m.IndexId == endInex.Id).ToList();
                    if (usefiles.Count() > 0 && ((indextype && indicatorCollection) || !indextype))//判断指标是否需要上传佐证材料
                    {
                        expertiseIndexOutput.Files = usefiles.Select(m => new IndexFileOutput
                        {
                            Id = m.Id,
                            Name = m.Name,
                            Remark = m.Remark,
                            SchoolId = m.SchoolId,
                            Type = m.Type,
                            IndexId = m.IndexId
                        }).ToList();
                        expertiseIndexOutput.SchoolName = school.Name;
                        expertiseIndexOutput.SchoolId = school.Id;
                        expertiseIndexOutput.SchoolType = school.SchoolType;
                        expertiseIndexOutput.XM_ID = endInex.Id;
                        var endIndexEtity = endIndexs.Where(a => a.Id == endInex.Id).FirstOrDefault();
                        expertiseIndexOutput.Name = /*endIndexEtity?.Sort + "." + */endIndexEtity?.Name;
                        expertiseIndexOutputList.Add(expertiseIndexOutput);
                    }
                }

                TargetZzFiles.Add(expertiseIndexOutputList.OrderBy(a => a.Sort).ToList());

            }

            var aliossConfig = _fileService.GetAliOSSConfig();
            OssClient client = new OssClient(aliossConfig.Endpoint, aliossConfig.AccessKeyId, aliossConfig.AccessKeySecret);
            foreach (var item in TargetZzFiles)//多个指标学校佐证文件
            {
                schoolFileOutputList = new List<SchoolFileOutput1>();
                foreach (var SchoolZzFiles in item)
                {
                    if (SchoolZzFiles.Files.Any())
                    {
                        foreach (var file in SchoolZzFiles.Files)
                        {
                            schoolFileOutput = new SchoolFileOutput1();
                            var model = files.Where(a => a.Id == file.Id).FirstOrDefault() ?? new IndexFileEntity();
                            if (model == null || string.IsNullOrEmpty(file.Id))
                            {
                                return Json(RongboResult<string>.Failed(-1, "文件不存在"));
                            }
                            string savePath = (_webEnv.ContentRootPath + AppSetting.GetFilePath() + model.Path).Replace("\\", "/");
                            if (System.IO.File.Exists(savePath))
                            {
                                var fs = new FileStream(savePath, FileMode.Open, FileAccess.Read);
                            }
                            else
                            {

                                var type = model.Type;
                                schoolFileOutput.FileTypeName = file.Name;
                                schoolFileOutput.SchoolName = SchoolZzFiles.SchoolName;
                                schoolFileOutput.Id = SchoolZzFiles.Id;
                                schoolFileOutput.Name = SchoolZzFiles.Name;
                                if (!string.IsNullOrWhiteSpace(type) && (type == "image/jpeg" || type == "image/png" || type == "image/gif"))
                                {
                                    type = "image/jpg";
                                }
                                if (client.DoesObjectExist(aliossConfig.BucketName, model.Path))
                                {
                                    url = GeneratePresignedUri(client, aliossConfig.BucketName, model.Path, DateTime.Now.AddHours(1), type);
                                    schoolFileOutput.Path = url;
                                    schoolFileOutputList.Add(schoolFileOutput);
                                }
                                else if (client.DoesObjectExist(aliossConfig.BucketName, model.DistrictCode + "/" + model.Path))
                                {
                                    url = GeneratePresignedUri(client, aliossConfig.BucketName, model.DistrictCode + "/" + model.Path, DateTime.Now.AddHours(1), type);
                                    schoolFileOutput.Path = url;
                                    schoolFileOutputList.Add(schoolFileOutput);

                                }
                            }
                        }

                    }
                    else
                    {
                        schoolFileOutput = new SchoolFileOutput1();
                        schoolFileOutput.SchoolName = SchoolZzFiles.SchoolName;
                        schoolFileOutput.FileTypeName = "";
                        schoolFileOutput.Id = SchoolZzFiles.Id;
                        schoolFileOutput.Name = SchoolZzFiles.Name;
                        schoolFileOutput.Path = "";
                        schoolFileOutputList.Add(schoolFileOutput);
                    }
                }
                schoolFileOutputLists.Add(schoolFileOutputList);
            }

            ApiResponse1<string> resultMessage = await DownTargetZzFile(schoolFileOutputLists);//压缩打包成zip格式文件
            return Json(RongboResult<string>.Failed(resultMessage.state, resultMessage.message));
        }

        /// <summary>
        /// OSS生成文件签名地址
        /// </summary>       
        private string GeneratePresignedUri(OssClient client, string bucketName, string key, DateTime expiration, string type)
        {
            ResponseHeaderOverrides responseHeaders = new ResponseHeaderOverrides();
            responseHeaders.ContentType = type;//"application/pdf"

            var request = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get)
            {
                Expiration = expiration,
                ResponseHeaders = responseHeaders
            };
            return client.GeneratePresignedUri(request).ToString();
        }


        /// <summary>
        /// 下载完成后删除压缩包
        /// </summary>
        /// <returns></returns>
        public IActionResult DeleteZip(string schoolName)
        {
            try
            {
                string pathZip = Directory.GetCurrentDirectory() + "/file/" + schoolName + "佐证资料.zip";
                if (System.IO.File.Exists(pathZip))
                {
                    //Directory.Delete(pathZip);
                    System.IO.File.Delete(pathZip);
                }
                return Json("");
            }
            catch (Exception)
            {
                return Json("");
            }
        }

以上,希望能够对各位有所帮助

相关推荐
liulilittle35 分钟前
OPENPPP2 1.0.0.26145 正式版发布:内核态 SYSNAT 性能飞跃 + Windows 平台避坑指南
开发语言·网络·c++·windows·通信·vrrp
分布式存储与RustFS1 小时前
Windows原生版RustFS:无需Docker,1分钟本地对象存储环境搭建
windows·docker·容器·对象存储·minio·企业存储·rustfs
xjt_09011 小时前
Oh My Codex 快速使用指南
windows
独隅1 小时前
在 Windows 上部署 TensorFlow 模型的全面指南
人工智能·windows·tensorflow
.生产的驴2 小时前
Vue3 超大字体font-slice按需分片加载,极速提升首屏速度, 中文分片加载方案,性能优化
前端·vue.js·windows·青少年编程·性能优化·vue·rescript
小白o菜2 小时前
Claude Code在windows部署,使用第三方api,如open router等
windows·claude·openrouter·aicodemirror·小鱼api
manyikaimen2 小时前
博派智能-运动控制技术-RTCP-五轴联动
c++·图像处理·qt·算法·计算机视觉·机器人·c#
代码小书生3 小时前
Windows X-Lite Win11 26H1 v3 游戏优化系统!集Win11、Win10、Win7三代优点,兼顾游戏办公生产算力,系统精简纯净
windows·游戏·windows x-lite·windows 游戏版·windows优化版·老电脑系统
被放养的研究生3 小时前
算法比赛用到的函数或模块(Python)
windows·python·算法
私人珍藏库3 小时前
[Windows] imFile下载器v1.2.0绿色版
windows·工具·软件·多功能