ASP.NET中如何保存客户端上传的图片?
解决ASP.NET图片上传并保存到文件夹的问题
一、修正模型类
原模型用List<string>无法接收上传的文件,需替换为List<IFormFile>(ASP.NET专门处理上传文件的类型),若需存储文件路径可新增属性:
public class ReportModel { /* Web stuff */ [DisplayName("Add photo")] public List<IFormFile> Photos { get; set; } // 接收上传的文件 public List<string> PhotoPaths { get; set; } // 存储保存后的文件相对路径(可选) /* More web stuff */ }
二、调整前端表单
必须添加enctype="multipart/form-data"才能正确上传文件,同时更新input绑定的属性:
<form method="post" enctype="multipart/form-data"> <div class="form-group"> <label asp-for="Photos" class="control-label"></label> <input asp-for="Photos" class="" type="file" id="file" accept="image/*" multiple /> <span asp-validation-for="Photos" class="text-danger"></span> </div> <div class="form-group" id="display_image" style="display: none; overflow-y: scroll; height: 400px; width: auto;"> <output id="result" style="overflow-y:scroll; height:400px; width:auto; "></output> </div> <!-- 其他表单元素 --> <button type="submit">提交报告</button> </form> <script> document.querySelector("#file").addEventListener("change", (e) => { if (window.File && window.FileReader && window.FileList && window.Blob) { const files = e.target.files; const output = document.querySelector("#result"); output.innerHTML = ""; for (let i = 0; i < files.length; i++) { if (!files[i].type.match("image")) continue; const picReader = new FileReader(); picReader.addEventListener("load", function (event) { const picFile = event.target; const div = document.createElement("div"); div.innerHTML = `<img class="form-control" src="${picFile.result}" title="${picFile.name}" style="height: 150px; width: auto; margin: 5px;"/>`; output.appendChild(div); }); picReader.readAsDataURL(files[i]); document.getElementById('display_image').setAttribute("style", "display:block;width:auto"); } } else { alert("你的浏览器不支持File API"); } }); </script>
注:调整了预览图片的样式,移除了冗余的onchange绑定。
三、后端控制器实现保存逻辑
注入IWebHostEnvironment获取网站根路径,将文件保存到wwwroot下的指定文件夹,并记录相对路径:
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using System.IO; public class ReportController : Controller { private readonly IWebHostEnvironment _webHostEnvironment; public ReportController(IWebHostEnvironment webHostEnvironment) { _webHostEnvironment = webHostEnvironment; } [HttpPost] public IActionResult Create(ReportModel model) { if (ModelState.IsValid) { if (model.Photos != null && model.Photos.Count > 0) { model.PhotoPaths = new List<string>(); // 定义保存文件夹路径:wwwroot/ReportPhotos string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "ReportPhotos"); // 文件夹不存在则创建 if (!Directory.Exists(uploadsFolder)) { Directory.CreateDirectory(uploadsFolder); } foreach (var photo in model.Photos) { if (photo.Length > 0) { // 生成唯一文件名,避免覆盖 string uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); // 保存文件到磁盘 using (var fileStream = new FileStream(filePath, FileMode.Create)) { photo.CopyTo(fileStream); } // 记录相对路径,用于前端显示或数据库存储 model.PhotoPaths.Add("/ReportPhotos/" + uniqueFileName); } } } // 此处可添加将ReportModel(含PhotoPaths)保存到数据库的逻辑 return RedirectToAction("Index"); } return View(model); } }
四、关键注意事项
- 文件夹权限:确保网站运行账户对
wwwroot/ReportPhotos有读写权限,否则保存会失败。 - 文件大小限制:ASP.NET默认限制上传文件大小,如需调整,在
Program.cs中配置:builder.Services.Configure<Microsoft.AspNetCore.Http.Features.FormOptions>(options => { options.MultipartBodyLengthLimit = 10485760; // 10MB,可按需修改 }); - 安全验证:前端
accept="image/*"仅为前端校验,后端需额外验证文件类型(如扩展名、MIME类型),防止恶意文件上传。
内容的提问来源于stack exchange,提问作者user16991782
相关产品推荐
相关产品推荐

