在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
首先在控制器中注入IWebHostEnvironment IWebHostEnvironment提供有关正在运行应用程序的Web托管环境的信息。 属于命名空间Microsoft.AspNetCore.Hosting IWebHostEnvironment接口需要注入为控制器依赖性再后来整个控制器使用。 该IWebHostEnvironment接口有两个属性。
private readonly IWebHostEnvironment _webHostEnvironment; public CommonController(IWebHostEnvironment webHostEnvironment) { _webHostEnvironment = webHostEnvironment; } 此处根据WebRootPath = "D:\\source\\repos\\AnnualMeeting\\Game\\wwwroot",把文件放在wwwroot目录下 文件上传使用IFormFile 1 [Route("api/[controller]")] 2 [ApiController] 3 public class CommonController : ControllerBase 4 { 5 private readonly IWebHostEnvironment _webHostEnvironment; 6 7 public CommonController(IWebHostEnvironment webHostEnvironment) 8 { 9 _webHostEnvironment = webHostEnvironment; 10 } 11 [HttpPost] 12 [Route("FileUpload")] 13 public async Task<IActionResult> FileUpload(IFormFile files) 14 { 15 16 if (files == null && files.Length <= 0) 17 { 18 throw new Exception("Files is Null"); 19 } 20 21 var fileExt = Path.GetExtension(files.FileName); 22 var newFileName = Guid.NewGuid().ToString() + fileExt; 23 var path = Path.Combine(_webHostEnvironment.WebRootPath, "Avatar\\" + newFileName); 24 try 25 { 26 await using var stream = System.IO.File.Create(path); 27 await files.CopyToAsync(stream); 28 return Ok(new { msg = "上传成功", fileName = newFileName }); 29 } 30 catch (Exception e) 31 { 32 throw new Exception(e.Message); 33 } 34 } 35 } 在swagger中可直接上传测试 |
请发表评论