在 ASP .NET MVC 中进行文件上传时,经常会遇到上传文件始终为 null 的问题。此问题通常由于未将 enctype 属性设置为 "multipart/form-data" 导致的。
以下是可能导致此问题的 HTML 表单示例:
将 enctype 属性设置为 "multipart/form-data" 将解决此问题:
在控制器中,您可以使用 HttpPostedFileBase 类型的参数来访问上传的文件:
[HttpPost] public ActionResult Upload(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { // Do something with the file return RedirectToAction("Success"); } else { return RedirectToAction("Error"); } }