基于.NET Core2的图片上传

时间:2021-12-15 23:37:46

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

   public async Task<IActionResult> Upload([FromServices]IHostingEnvironment environment)
{ var data = new PicData();
string path = string.Empty;
var files = Request.Form.Files.Where(c => c.Name == "MyPhoto01");
if (files == null || files.Count() <= ) { data.Msg = "请选择上传的文件。"; return Json(data); }
//格式限制
var allowType = new string[] { "image/jpg", "image/png" };
if (files.Any(c => allowType.Contains(c.ContentType)))
{
if (files.Sum(c => c.Length) <= * * )
{
foreach (var file in files)
{
string strpath = Path.Combine("Upload", DateTime.Now.ToString("MMddHHmmss") + file.FileName);
path = Path.Combine(environment.WebRootPath, strpath); using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
await file.CopyToAsync(stream);
}
}
data.Msg = "上传成功";
return Json(data);
}
else
{
data.Msg = "图片过大";
return Json(data);
}
}
else {
data.Msg = "图片格式错误";
return Json(data);
}
}
public class PicData
{
public string Msg { get; set; }
}

注意:([FromServices]IHostingEnvironment environment,一定要加上FromServices这个特性!!!