Skip to content Skip to sidebar Skip to footer

Asp.net Mvc 5 Image Upload To Folder

I have a very simple MVC5 application that has a product page for the client that I also am utilizing the basic CRUD operations that have been scaffolded out in MVC 5. I have a Mo

Solution 1:

You'll need to:

  • add an input of type file to your form,
  • have the attribute on your form element enctype = "multipart/form-data"

Then add an HttpPostedFileBase to your model with the same name as the name of the input. Then the HttpPostedFileModelBinder will populate the model property from the uploaded file before the action is invoked. Note, I think you should probably add in the model id somewhere, perhaps as a path element, to guaranteed uniqueness in the image path so that images don't accidentally get overwritten.

There's a reasonably complete discussion of this at http://www.prideparrot.com/blog/archive/2012/8/uploading_and_returning_files

publicclassCakes
{
    ...

    public HttpPostedFileBase UploadedFile { get; set; }

}

[HttpPost]
public ActionResult Edit(Cakes cake) // I'd probably use a view model here, not the domain model
{
      if (ModelState.IsValid)
      {
           if (cakes.UploadedFile != null)
           {
               cakes.UploadedFile.SaveAs(Path.Combine("path-to-images-for-this-cake", cakes.CakeImage));
           }

           ....
      }
}

Solution 2:

The code that was supplied here eventually went into building this small demo that allows you to upload images to the file system and use them dynamically without storing any values to the database; however you will have the string to the images file location as part of your Model class which uses a convention and naming of the uploaded file to display.

I would like to upload this to github and see if I can't get some others to help me work out a better solution that uses this idea. Thinking of making it work with MongoDB too.

ASP.NET MVC 5 Image Upload & Delete w/ Calculated Property

Post a Comment for "Asp.net Mvc 5 Image Upload To Folder"