ASP.NET Core 文件上传
以下是将上传的图片保存在本地的示例代码:
1、在前端,使用HTML表单元素和POST方法将文件上传到后端:
<form method="post" enctype="multipart/form-data" action="/upload"> <input type="file" name="image" /> <button type="submit">Upload</button> </form>
2、在后端,使用IFormFile
接口和FileStream
类将上传的文件保存到本地磁盘上:
[HttpPost("upload")] public async Task<IActionResult> Upload(IFormFile image) { if (image == null || image.Length == 0) { return BadRequest("Invalid file"); } var filePath = Path.Combine(Path.GetTempPath(), image.FileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await image.CopyToAsync(stream); } return Ok(); }