尝试使用 mvc 上传文件时,请求文件为空
本文关键字:文件 请求 mvc | 更新日期: 2023-09-27 18:31:01
这是我的模型。
public class Libro
{
[Key]
[ScaffoldColumn(false)]
public int ID { get; set; }
[Required]
[MaxLength(300, ErrorMessage = "El Path debe tener como máximo 300 caractéres")]
[Display(Name = "Ruta de acceso")]
public string Path { get; set; }
[Required]
[MaxLength(80, ErrorMessage = "El nombre debe tener como máximo 80 caractéres")]
public string Nombre { get; set; }
[Required]
[Display(Name = "Ruta de acceso")]
public HttpPostedFileBase File { get; set; }
//Relations
public virtual ICollection<Hoja> Hojas { get; set; }
}
以下是我的观点:
@model xx.Models.Libro
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Libro</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.File, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(x => x.File, new { type = "file" })
@*@Html.EditorFor(model => model.File, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.File, "", new { @class = "text-danger" })*@
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Nombre, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Nombre, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Nombre, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
控制器
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Nombre")] Libro libro)
{
if (ModelState.IsValid)
{
foreach (string upload in Request.Files)
{
if (Request.Files[upload].ContentLength == 0) continue;
string pathToSave = Server.MapPath("~/App_Data/Uploads");
string filename = Path.GetFileName(Request.Files[upload].FileName);
Request.Files[upload].SaveAs(Path.Combine(pathToSave, filename));
libro.Path = Path.Combine(pathToSave, filename);
db.Libro.Add(libro);
db.SaveChanges();
}
return RedirectToAction("Index");
}
return View(libro);
}
您需要将
表单上的encType
设置为multipart/form-data
;
@using (Html.BeginForm("Create", "ControllerName", FormMethod.Post,
new { encType="multipart/form-data" }))
该文件也将从您的模型中提供,即 libro.File
.
尝试将BeginForm
更改为:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post,
new { enctype = "multipart/form-data" }))