i'm trying to upload a file with ASP MVC4, i give you my situation:
- I have a model class "Movie" with some atributes (doesn't matter)
- I want to add some code to my controller and View part without touching the model, because we want to make the image difrent to the model.
So, here's an example of my view code, i'll bold the lines added by me:
@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>
So you can see that i have some code generated by ASP which allows me to add a new user to the db, and a "input" added by me to upload the image.
The problem is that when i try to recover that image from the controller, the "Request.Files" atributte is empty, so i can't recover any image, and of course i can't upload it, here's my controller code:
[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);
}
Don't know why the "Request.Files" is empty, so if anyone can help me it would be great, Thank you so much