/// <summary> /// 上传文件 /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <AttachmentDto> UploadFile([FromForm] UploadFileInput input) { CheckContentType(input); var attachment = new Attachment(GuidGenerator.Create()) { Name = input.File.FileName, Length = input.File.Length, Extension = input.File.ContentType, AttachmentApplyType = input.AttachmentApplyType }; var dir = _config["AttachmentPath"] + input.AttachmentApplyType + "/"; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } using (FileStream fileStream = System.IO.File.Create(dir + input.File.FileName)) { await input.File.CopyToAsync(fileStream); fileStream.Flush(); } var result = await _attachmentRepository.InsertAsync(attachment); return(ObjectMapper.Map <Attachment, AttachmentDto>(result)); }
/// <summary> /// 检查类型 /// </summary> /// <param name="input"></param> /// <returns></returns> protected void CheckContentType(UploadFileInput input) { switch (input.AttachmentApplyType) { case AttachmentApplyType.Picture: case AttachmentApplyType.Logo: if (!input.File.ContentType.StartsWith("image", StringComparison.CurrentCultureIgnoreCase)) { throw new UserFriendlyException("仅支持上传JPG、JPEG、PNG等图片文件"); } break; case AttachmentApplyType.Video: if (!input.File.ContentType.StartsWith("video", StringComparison.CurrentCultureIgnoreCase)) { throw new UserFriendlyException("仅支持上传avi、wma、MP4等图片文件"); } break; default: break; } }