0

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

3 Answers 3

3

Try the below:

[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);
}
Sign up to request clarification or add additional context in comments.

6 Comments

Sorry for the short answer. Short on time right now. fileUpload should bind to fileUpload in Create(Movie movie, HttpPostedFile fileUpload). Then do your magic.
Why does this should work? need i to touch something in the View? I'm testing it right now, i'll tell you if it worked ;)
i'm sorry, it doesn't work, if i add your second param, and your lines, the "if" modelState.IsValid is equal to false, so it doesn't execute my magic :P
Also, modify this: <input type="file" name="fileUpload" id="fileUpload" />
Also, can you paste your Model/Class ?
|
1

Lets see if we can find out whats wrong. Try the following and show us the errors:

[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);
 }

5 Comments

still working on that, i got a blue-screen :D i love Windows lol
ok, i got the error:(i'll translate the output from spanish) System.InvalidOperationException: Error converting the param from 'System.String' to the type 'System.Web.HttpPostedFile' because there's any conversor that can convert that types.
Change your View: @using (Html.BeginForm("Create","HomeController",FormMethod.Post,new {enctype="multipart/form-data"})) { And of course change HomeController to your Controller's name. enctype="multipart/form-data" should do the trick.
I'm gonna link your answer as solved, we could solve our problem using your answer ;) we changed the model and added a new Param, then it was easy, using your answer everything worked!! :D Thank you so much
Glad i could help. Sorry i didnt see this earlier, but its monday morning and i need more coffee ;)
0

Antevirus has the answer but I hat to dig into comments to find it out. In short the problem for was that I didnt specify any encodings for my form which is

enctype = "multipart/form-data"

Here is the full code:

@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>
}

I am using file-input for bootstrap

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.