基於.NET Core2的圖片上傳

其實,.NET Core2的圖片上傳挺好作的,只是,有些坑要注意。。。。。。。話很少說,上代碼async

 1   public async Task<IActionResult> Upload([FromServices]IHostingEnvironment environment)
 2         {
 3             
 4             var data = new PicData();
 5             string path = string.Empty;
 6             var files = Request.Form.Files.Where(c => c.Name == "MyPhoto01");
 7             if (files == null || files.Count() <= 0) { data.Msg = "請選擇上傳的文件。"; return Json(data); }
 8             //格式限制
 9             var allowType = new string[] { "image/jpg", "image/png" };
10             if (files.Any(c => allowType.Contains(c.ContentType)))
11             {
12                 if (files.Sum(c => c.Length) <= 1024 * 1024 * 4)
13                 {
14                     foreach (var file in files)
15                     {
16                         string strpath = Path.Combine("Upload", DateTime.Now.ToString("MMddHHmmss") + file.FileName);
17                         path = Path.Combine(environment.WebRootPath, strpath);
18 
19                         using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
20                         {
21                             await file.CopyToAsync(stream);
22                         }
23                     }
24                     data.Msg = "上傳成功";
25                     return Json(data);
26                 }
27                 else
28                 {
29                     data.Msg = "圖片過大";
30                     return Json(data);
31                 }
32             }
33             else
34 
35             {
36                 data.Msg = "圖片格式錯誤";
37                 return Json(data);
38             }
39         }
40 public class PicData
41     {
42         public string Msg { get; set; }
43     }

注意:([FromServices]IHostingEnvironment environment,必定要加上FromServices這個特性!!!spa

相關文章
相關標籤/搜索