如何在ASP.NET Core MVC中用C#实现服务器图片保存?解决类型报错
ASP.NET Core MVC 图片上传:替代HttpPostedFileBase的实现方案
ASP.NET Core MVC中已经弃用了HttpPostedFileBase(这是ASP.NET Framework专属的类型),你需要改用IFormFile来处理文件上传。这个类型属于Microsoft.AspNetCore.Http命名空间,默认已包含在ASP.NET Core MVC项目中,无需额外安装NuGet包。
修改后的控制器代码
using Microsoft.AspNetCore.Http; using System.IO; using Microsoft.AspNetCore.Mvc; public class UploadController : Controller { [HttpPost] public async Task<IActionResult> UploadFile(IFormFile file) { try { if (file != null && file.Length > 0) { string fileName = Path.GetFileName(file.FileName); // 构建保存路径 var savePath = Path.Combine(Directory.GetCurrentDirectory(), "Images", fileName); // 确保Images文件夹存在,避免目录不存在报错 var directory = Path.GetDirectoryName(savePath); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } // 异步保存文件(同步场景可改用file.CopyTo(stream)) using (var stream = new FileStream(savePath, FileMode.Create)) { await file.CopyToAsync(stream); } ViewBag.Message = "文件上传成功!"; } else { ViewBag.Message = "请选择要上传的文件!"; } } catch { ViewBag.Message = "文件上传失败!"; } return View("Index"); } }
视图代码(可保留原写法,或优化为Tag Helper)
原视图代码可以直接继续使用,若想贴合ASP.NET Core的最佳实践,也可以改用Tag Helper写法:
@using (Html.BeginForm("UploadFile", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" })) { <div> <input asp-for="file" type="file" /><br /> <input type="submit" value="上传" /> @ViewBag.Message </div> }
注意:如果使用
asp-for,需要在对应的视图模型中添加IFormFile file属性;保持原有的@Html.TextBox写法也完全可行。
关键修改点说明
- 参数类型替换:用
IFormFile替代HttpPostedFileBase - 文件长度判断:用
file.Length替代file.ContentLength - 文件保存方式:Core中不再提供
SaveAs方法,改用CopyTo或CopyToAsync写入文件流 - 目录检查:添加文件夹存在性判断,避免因目录不存在导致上传失败
内容的提问来源于stack exchange,提问作者F205
相关产品推荐
相关产品推荐

