在 Web 應用程序開發過程當中,老是沒法避免涉及到文件上傳,此次咱們來聊一聊怎麼去實現一個簡單方即可複用文件上傳功能;經過建立自定義綁定模型來實現文件上傳。git
FromBodyAttribute FromFromAttribute FromQueryAttribute FromHeaderAttribute FromServicesAttribute FromRouteAttribute
[HttpPost] public async Task<IActionResult> PostInfo([FromBody]UserInfo user,[FromQuery] string city) { ... }
public class FromFileAttribute : Attribute, IBindingSourceMetadata { public BindingSource BindingSource => BindingSource.FormFile; }
public class UserFile { public string FileName { get; set; } public long Length { get; set; } public string Extension { get; set; } public string FileType { get; set; } private readonly static string[] Filters = { ".jpg", ".png", ".bmp" }; public bool IsValid => !string.IsNullOrEmpty(this.Extension) && Filters.Contains(this.Extension); private IFormFile file; public IFormFile File { get { return file; } set { if (value != null) { this.file = value; this.FileType = this.file.ContentType; this.Length = this.file.Length; this.Extension = this.file.FileName.Substring(file.FileName.LastIndexOf('.')); if (string.IsNullOrEmpty(this.FileName)) this.FileName = this.file.FileName; } } } public async Task<string> SaveAs(string destinationDir = null) { if (this.file == null) throw new ArgumentNullException("沒有須要保存的文件"); if (destinationDir != null) Directory.CreateDirectory(destinationDir); var newName = DateTime.Now.Ticks; var newFile = Path.Combine(destinationDir ?? "", $"{newName}{this.Extension}"); using (FileStream fs = new FileStream(newFile, FileMode.CreateNew)) { await this.file.CopyToAsync(fs); fs.Flush(); } return newFile; } }
[HttpPost] public async Task<IActionResult> Post([FromFile]UserFile file) { if (file == null || !file.IsValid) return new JsonResult(new { code = 500, message = "不容許上傳的文件類型" }); string newFile = string.Empty; if (file != null) newFile = await file.SaveAs("/data/files/images"); return new JsonResult(new { code = 0, message = "成功", url = newFile }); }
3.2 首先是在 Post([FromFile]UserFile file) 中使用上面建立的 FromFileAttribute 對模型 UserFile 進行綁定,而後驗證文件是否正確,接下來經過 file.SaveAs("/data/files/images"); 保存文件github
3.3 上傳代碼很是簡單,幾乎到了沒法精簡的程度,最終發揮做用的就是 file.SaveAs 操做async
(經 海闊天空XM. 提醒,因爲上傳了編譯後的 dll 引發部分朋友殺毒軟件誤報,現已從新上傳,感謝!)測試
https://github.com/lianggx/EasyAspNetCoreDemo/tree/master/Ron.UploadFilethis