我正在尝试使用ASP MVC4上传文件,我告诉你我的情况:
所以,这是我的视图代码示例,我将粗略添加由我添加的行:
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Movie</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Duration)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Duration)
@Html.ValidationMessageFor(model => model.Duration)
</div>
//ADDED BY ME:
<div class="editor-label">
<p>Select a file</p>
</div>
<div class="editor-field">
<input type="file" name="fileUpload" />
</div>//END OF MY CODE
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
所以你可以看到我有一些ASP生成的代码,它允许我向数据库添加一个新用户,并添加一个“输入”来上传图像。
问题是,当我尝试从控制器恢复该图像时,“Request.Files”atributte为空,所以我无法恢复任何图像,当然我无法上传它,这是我的控制器代码:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Movie movie)
{
if (ModelState.IsValid)
{
db.MovieContext.Add(movie);
db.SaveChanges();
foreach (string file in Request.Files)
{
var postedFile = Request.Files[file];
postedFile.SaveAs(Server.MapPath("~/UploadedFiles") + pelicula.Id);
}
return RedirectToAction("Index");
}
return View(movie);
}
不知道为什么“Request.Files”是空的,所以如果有人能帮助我,那就太棒了,非常感谢你
答案 0 :(得分:3)
尝试以下方法:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Movie movie, HttpPostedFile fileUpload)
{
if (ModelState.IsValid)
{
db.MovieContext.Add(movie);
db.SaveChanges();
var postedFile = fileUpload;
postedFile.SaveAs(Server.MapPath("~/UploadedFiles") + pelicula.Id);
return RedirectToAction("Index");
}
return View(movie);
}
答案 1 :(得分:1)
让我们看看我们是否能找出错误的信息。请尝试以下操作并向我们显示错误:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Movie movie, HttpPostedFile fileUpload)
{
if (ModelState.IsValid)
{
db.MovieContext.Add(movie);
db.SaveChanges();
var postedFile = fileUpload;
postedFile.SaveAs(Server.MapPath("~/UploadedFiles") + pelicula.Id);
return RedirectToAction("Index");
}
var content = "";
foreach (ModelState modelState in ViewData.ModelState.Values)
{
foreach (ModelError error in modelState.Errors)
{
content += error.ErrorMessage + ", " + error.Exception + "<br/>";
}
}
return Content(content);
//return View(movie);
}
答案 2 :(得分:0)
Antevirus有答案但我倾向于深入评论以找出答案。简而言之,问题是我没有为我的表单指定任何编码
enctype = "multipart/form-data"
以下是完整代码:
@using (Html.BeginForm("Create", "Members", FormMethod.Post, new { @id = "member-form", @enctype = "multipart/form-data" }))
{
<div class="form-group">
<label class="control-label col-md-2">Picture</label>
<div class="col-md-10">
<input id="fileUpload" type="file" name="fileUpload" class="file-loading">
</div>
</div>
}