Uploading an image and then displaying it is a very common requirement for any web application. Recently I was required to allow a user to add a profile picture and later on display it on his/her dashboard.

So here is what I had done, hope this helps you too.

Razor Code

@using (Html.BeginForm("SaveSettings", "Blog", FormMethod.Post, new { enctype="multipart/form-data"}))
{
    @Html.TextBoxFor(m => m.BlahBlah)

    // and more...

    <input type="file" name="file" id="file" />
    <input type="submit" name="submitButton" value="Save" />
}

The important thing to note here is we have added an html property called enctype as enctype="multipart/form-data".

Next up, the action method for this form. The action accepts two input parameters :

  • UserModel model : has all data entered in the form.
  • HttpPostedFileBase file : here is where you will have your uploaded image posted to.

Code

[HttpPost]
public ActionResult Index(UserModel model, HttpPostedFileBase file)
{

if (file.ContentLength > 0) {

    // code for saving the image file to a physical location.
    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/Uploads/Profile"), fileName);
    file.SaveAs(path);

    // prepare a relative path to be stored in the database and used to display later on.
    path = Url.Content(Path.Combine("~/Uploads/Profile", fileName));
    // save to db

    return RedirectToAction("Index");

}

You may sometime also require to upload multiple images, that too isn’t difficult below is the code for that. Using IEnumerable.

Razor Code

@using (Html.BeginForm("SaveSettings", "Blog", FormMethod.Post, new { enctype="multipart/form-data"}))
{
    <input type="file" name="file" id="file" /> <input type="file2" name="file2" id="file2" /> <input type="submit" name="submitButton" value="Save" />
}

and here is how you will be reading the files posted.

[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {
    foreach (var file in files) {

        // iterate through each file here...
    }
    return RedirectToAction("Index");
}

Now that you have uploaded the image and saved the image path, the next task is to display the image.

Displaying the uploaded image

<img width="200px" height="150px" src="@Url.Content(Model.ImageFilePath)"/>

Cheers !

**References **

http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx

http://stackoverflow.com/questions/7321383/displaying-an-uploaded-image-in-mvc-3-razor

http://stackoverflow.com/a/5248365/1182982