- 在模型中添加一个属性来存储图像文件:
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
public HttpPostedFileBase ImageFile { get; set; }
}
- 在视图中使用表单和文件上传控件来上传图像:
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) {
@Html.AntiForgeryToken()
}
- 在控制器中处理图像上传并将其保存到磁盘:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(MyModel model)
{
if (ModelState.IsValid)
{
if (model.ImageFile != null && model.ImageFile.ContentLength > 0)
{
var fileName = Path.GetFileName(model.ImageFile.FileName);
var path = Path.Combine(Server.MapPath("~/Images"), fileName);
model.ImageFile.SaveAs(path);
}
// Save your model to the database and redirect to a success page
// ...
return RedirectToAction("Index");
}
return View(model);
}