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("");}}
以上,希望能够对各位有所帮助