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

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

相关推荐
神仙别闹21 分钟前
基于C#+SQL Server实现(Web)学生选课管理系统
前端·数据库·c#
向宇it1 小时前
【unity组件介绍】URP Decal Projector贴花投影器,将特定材质(贴花)投影到场景中的其他对象上。
游戏·3d·unity·c#·游戏引擎·材质
joe02359 小时前
电脑安装 Win10 提示无法在当前分区上安装Windows的解决办法
windows·gpt·电脑·uefi
前端 贾公子9 小时前
vue-cli 模式下安装 uni-ui
前端·javascript·windows
斯是 陋室10 小时前
在CentOS7.9服务器上安装.NET 8.0 SDK
运维·服务器·开发语言·c++·c#·云计算·.net
Elastic 中国社区官方博客11 小时前
在 Windows 上使用 Docker 运行 Elastic Open Crawler
大数据·windows·爬虫·elasticsearch·搜索引擎·docker·容器
inwith12 小时前
C#语法基础总结(超级全面)(二)
开发语言·c#
CIAS14 小时前
clonezilla 导出自动化恢复iso
linux·windows·clonezilla
墨菲安全15 小时前
Node.js Windows下路径遍历漏洞
windows·node.js·路径遍历漏洞
NoirSeeker15 小时前
在windows平台上基于OpenHarmony sdk编译三方库并暴露给ArkTS使用(详细)
c++·windows·arkts·鸿蒙·交叉编译