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("");
            }
        }

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

相关推荐
Abigail_chow4 小时前
EXCEL如何快速批量给两字姓名中间加空格
windows·microsoft·excel·学习方法·政务
无味无感5 小时前
ASP.NET Core使用Quartz部署到IIS资源自动被回收解决方案
.netcore
MoFe15 小时前
【.net core】天地图坐标转换为高德地图坐标(WGS84 坐标转 GCJ02 坐标)
java·前端·.netcore
绿荫阿广6 小时前
互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(五):使用.NET为树莓派开发Wifi配网功能
c#·.net
love530love6 小时前
【笔记】在 MSYS2(MINGW64)中正确安装 Rust
运维·开发语言·人工智能·windows·笔记·python·rust
代码搬运媛7 小时前
“packageManager“: “[email protected]“ 配置如何正确启动项目?
windows·webpack
小道士写程序8 小时前
Qt 5.12 上读取 .xlsx 文件(Windows 平台)
开发语言·windows·qt
ou.cs8 小时前
c# :this() 和 :base()区别
开发语言·c#
汪小白JIY11 小时前
【C#】异步和多线程
c#·thread·async·task·threapool
宝桥南山13 小时前
DeepSeek - 尝试一下GitHub Models中的DeepSeek
microsoft·ai·微软·c#·github·.net