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

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

相关推荐
人猿泰飞38 分钟前
【AI训练环境搭建】在Windows11上搭建WSL2+Ubuntu22.04+Tensorflow+GPU机器学习训练环境
windows·ubuntu·机器学习·wsl·gpu训练
十步杀一人_千里不留行1 小时前
面向 C# 初学者的完整教程
开发语言·c#
LcVong1 小时前
一篇文章学会开发第一个ASP.NET网页
后端·c#·asp.net·web
Lilith的AI学习日记4 小时前
n8n 中文系列教程_05.如何在本机部署/安装 n8n(详细图文教程)
运维·windows·macos·ai编程·n8n
广龙宇4 小时前
【一起学Rust】使用Thunk工具链实现Rust应用对Windows XP/7的兼容性适配实战
开发语言·windows·rust
扛枪的书生5 小时前
Windows 提权指南
windows·渗透·kali·提权
qq_431331355 小时前
Unity ML-Agents + VScode 环境搭建 Windows
windows·vscode·unity·强化学习
h39745 小时前
MFC文件-屏幕录像
c++·windows·音视频·mfc