我是 MVC 4 的新手,我正在尝试在我的网站中实现文件上传控制。我找不到错误。我的文件中出现空值。
控制器:
public class UploadController : BaseController { public ActionResult UploadDocument() { return View(); } [HttpPost] public ActionResult Upload(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/Images/"), fileName); file.SaveAs(path); } return RedirectToAction("UploadDocument"); } }
看法:
@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" })) { <input type="file" name="FileUpload" /> <input type="submit" name="Submit" id="Submit" value="Upload" /> }
Upload方法的参数HttpPostedFileBase必须与file input.
Upload
HttpPostedFileBase
file input
所以只需将输入更改为:
<input type="file" name="file" />
此外,您可以在以下位置找到文件Request.Files:
Request.Files
[HttpPost] public ActionResult Upload() { if (Request.Files.Count > 0) { var file = Request.Files[0]; if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/Images/"), fileName); file.SaveAs(path); } } return RedirectToAction("UploadDocument"); }