基于.NET Core2的图片上传

其实,.NET Core2的图片上传挺好做的,只是,有些坑要注意。。。。。。。话不多说,上代码

 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这个特性!!!

 

posted @ 2017-12-19 10:54  Mr凯撒  阅读(1537)  评论(2编辑  收藏  举报