public class ImgController : ControllerBase { private readonly IHostEnvironment _environment; public ImgController(IHostEnvironment environment) { _environment = environment; } /// <summary> /// 上传图片 /// </summary> /// <param name="file"></param> /// <returns></returns> /// <exception cref="Exception"></exception> [HttpPost] public async Task<IActionResult> UploadFiles(IFormFile file) { if (file == null) return new OkObjectResult("请选择你要上传的图片!"); var images = new string[] { ".png", ".gif", ".jpg", ".bmp", ".jpeg" }; if (!images.Any(x => file.FileName.EndsWith(x))) return new OkObjectResult("上传图片格式有误!"); if (file.Length > 10 * 1024 * 1024) return new OkObjectResult("图片大小不可大于10MB!"); string fileExt = file.FileName.Substring(file.FileName.LastIndexOf('.')); //文件扩展名 string newFileName = Guid.NewGuid().ToString("N") + fileExt; var filePath = Path.Combine(_environment.ContentRootPath + "/wwwroot/imgs/" + newFileName) ; //判断当前路径是否存在 if (!Directory.Exists(filePath)) { using var stream = new FileStream(filePath, FileMode.Create); file.CopyTo(stream); stream.Flush(); return new OkObjectResult("上传成功!"); } return BadRequest("上传失败,服务器内部错误!"); } }