无法在ASP中上载图像.NET MVC4
本文关键字:图像 NET MVC4 上载 ASP | 更新日期: 2023-09-27 17:59:07
我无法在MVC应用程序中上传图像。有人知道我该如何修复这个错误吗?
模型图像:
namespace HelloWorld.Models
{
public class Image
{
[Required]
[DataType(DataType.MultilineText)]
public string ImagePath { get; set; }
public int ImageId { get; set; }
}
}
索引视图:
@model IEnumerable<HelloWorld.Models.Image>
@{
ViewBag.Title = "Index";
}
<p>
@Html.ActionLink("Create New", "Create")
</p>
@foreach (var item in Model) {
<img src="@Html.DisplayFor(modelItem => item.ImagePath)">
}
创建视图:
@model HelloWorld.Models.Image
@{
ViewBag.Title = "Create";
}
<form method="post" action="@Url.Action("Create", "Images")">
<div>
<h4>Image</h4>
<hr />
<input type="file" name="file">
<input type="submit" value="Upload">
</div>
</form>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
创建操作:
[HttpPost]
public ActionResult Create(Image img, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
file.SaveAs(HttpContext.Server.MapPath("../../Content/img/upload/") + file.FileName);
img.ImagePath = file.FileName;
}
db.Images.Add(img);
db.SaveChanges();
return RedirectToAction("Index");
}
return RedirectToAction("Create","Images");
}
我想我的问题是我的模型状态无效。因为我有RedirectToAction("创建"、"图像");
当您发布文件时,您需要在表单上包含多部分/表单数据enctype。
<form method="post" action="@Url.Action("Create", "Images")" enctype="multipart/form-data">
<div>
<h4>Image</h4>
<hr />
<input type="file" name="file">
<input type="submit" value="Upload">
</div>
</form>
更新
为文件创建视图模型
public class FileViewModel
{
[Required]
public HttpPostedFileBase file { get; set; }
}
然后更新你的行动如下
[HttpPost]
public ActionResult Create(FileViewModel model)
{
if (ModelState.IsValid)
{
var image = new Image();
model.SaveAs(HttpContext.Server.MapPath("../../Content/img/upload/") + model.FileName);
image.ImagePath = model.FileName;
db.Images.Add(image);
db.SaveChanges();
return RedirectToAction("Index");
}
return RedirectToAction("Create", "Images");
}