/// <summary> /// 保存文件 /// </summary> /// <param name="formFile">文件</param> /// <param name="relativePath">相对目录</param> /// <param name="rootPath">根目录</param> /// <param name="cancellationToken">取消token</param> /// <returns></returns> private async Task <FileInfo> UploadSave(IFormFile formFile, string relativePath, string rootPath, CancellationToken cancellationToken = default) { var date = DateTime.Now; var name = formFile.FileName; var size = formFile.Length; var fileInfo = new FileInfo(name, size) { Path = Path.Combine(relativePath, date.ToString("yyyy"), date.ToString("MM"), date.ToString("dd")), }; fileInfo.SaveName = $"{Guid.NewGuid().ToString().Replace("-", "")}.{fileInfo.Ext}"; var fullDir = Path.Combine(rootPath, fileInfo.Path); if (!Directory.Exists(fullDir)) { Directory.CreateDirectory(fullDir); } //写入 var fullPath = Path.Combine(fullDir, fileInfo.SaveName); fileInfo.Md5 = await SaveWidthMd5(formFile, fullPath, cancellationToken); return(fileInfo); }
public async Task <IResultModel <AttachmentUploadResultModel> > Upload(AttachmentUploadModel model, FileInfo fileInfo) { var result = new ResultModel <AttachmentUploadResultModel>(); var entity = new AttachmentEntity { Module = model.Module, Group = model.Group, FileName = fileInfo.FileName, SaveName = fileInfo.SaveName, Ext = fileInfo.Ext, Md5 = fileInfo.Md5, Path = fileInfo.Path, FullPath = Path.Combine(fileInfo.Path, fileInfo.SaveName), Size = fileInfo.Size.Size, SizeCn = fileInfo.Size.ToString() }; var mediaType = await _mediaTypeRepository.GetByExt(fileInfo.Ext); if (mediaType != null) { entity.MediaType = mediaType.Value; } using (var tran = _repository.BeginTransaction()) { if (await _repository.AddAsync(entity)) { //如果需要授权访问附件,需要添加拥有者关联信息 if (!model.Auth || await _ownerRepository.AddAsync(new AttachmentOwnerEntity { AttachmentId = entity.Id, AccountId = model.AccountId }, tran)) { tran.Commit(); var resultModel = _mapper.Map <AttachmentUploadResultModel>(entity); return(result.Success(resultModel)); } } } return(result.Failed("上传失败")); }