webapi文件上传

webapi文件上传

  1. public async Task<JsonResult<ResultInfo>> PublishingNews([SwaggerFileUpload] string title, string content) 

  2. FileInfo fileinfo = null
  3. //是否上传了图片 
  4. if (Request.Content.IsMimeMultipartContent()) 

  5. //这里路径是服务器虚拟路劲,也就是文件要保存的地方 
  6. var provider = new ExtensionMultipartFormDataStreamProvider(GetCurrentFilePaht(VirtualPath)); 
  7. try 

  8. //异步保存文件 
  9. await Request.Content.ReadAsMultipartAsync(provider); 
  10. //遍历多文件获取文件信息 
  11. foreach (MultipartFileData file in provider.FileData) 

  12. fileinfo = new FileInfo(file.LocalFileName); 
  13. //过滤文件类型 
  14. string fileFilt = ".gif|.jpg|.php|.jsp|.jpeg|.png|......"
  15. if (string.IsNullOrEmpty(fileinfo.Extension) || fileFilt.IndexOf(fileinfo.Extension) <= -1

  16. //删除文件 
  17. fileinfo.Delete(); 
  18. return Json(ResultOperationFailed("只能上传图片", "图片上传失败!")); 


  19.  

  20. catch (System.Exception e) 

  21. return Json(ResultOperationFailed(e.Message,"图片上传失败!")); 


posted @ 2017-06-21 10:43  明明.如月  阅读(260)  评论(0编辑  收藏  举报