Freelance Web Development in Malta


Uploading Images in ASP.NET MVC

First of all I would like to welcome any first time visitors to my blog. Before I start this blog I would like to give a brief introduction to myself. My name is Mark Anthony Farrugia and, apart from being a Computing Teacher, I am a freelance web developer based in Malta, a small island in the Mediterranean. So now let me start this blog post :) .

The outcomes of this blog are to

  1. Discover how we can upload an image back to our server
  2. Understand when and how we can use IF conditions using Razor syntax
  3. Display a Product Image back in our View
  4. Understand how we can use the RedirectToAction and passing data back to out controller

The prerequisites of this blog are

  1. You should have a Products table which has a specific field of type Varchar which will store the image path
  2. You should have some understanding of LINQ To Entities
  3. You should have SQL Server Express installed. You can download it from here.
  4. You should have an Images and then Products subfolder in your project where we will be saving the uploaded image

In this blog I will be writing on how you can upload an Image back to a server using ASP.NET MVC. For those of you who are familiar with ASP.NET will find that the way this is done using ASP.NET MVC is somewhat different. In ASP.NET you would use the FileUpload control which takes care of most of the functionality.

So first things first. Let’s start by modifying our Edit Product View we have created in this blog. We will be adding an HTML form tag which basically is a form which posts back to a Controller action method which saves the image back to the server, and updates the relevant product with the image path. The Controller action method’s name is UploadProductImage and will accept a ProductId parameter. The underneath code snippet is the actual code which should be placed in our ASP.NET MVC View.

<form id="productimageuploadform" action="/Products/UploadProductImage" method="post" name="productimageuploadform" enctype="multipart/form-data">
  <input id="ProductId" type="hidden" name="ProductId" value="@Model.ProductId" />
 <input id="imguploadproductimage" title="Upload a product image" type="file" name="imguploadproductimage" />
 <input title="Upload image" type="submit" value="Upload" /></form>

Let me explain the above code. In the first line I am creating a form which posts back to the Products/UploadProductImage controller method. Note that a form which will upload an image should have the attribute enctype set to multipart/form-data. If this is not set the image will not be uploaded.

In the second line I am creating a hidden HTML field which stores the ProductId so that this will be passed back to our controller method. You will note that the Controller method has a single parameter also called ProductId. MVC will then map this hidden field value to the ProductId parameter inside the Edit Product controller method, since they have the same name. Recall that in this blog we created a Controller method which returns a single Product back to our Edit View. Thus I am using Razor syntax @Model.ProductId which basically returns the ProductId which is returned from our HttpGet Edit Product controller method.

In line 3 and 4 I am just creating an HTML input file control which basically will allow the user to select an image and a submit button which actually submits back to our Controller method.

Run your application and you should have a View as shown in Figure 1. Please note that this View is a continuation of the Product View we have created in this blog.

Product Upload Image View

Figure 1 – ASP.NET MVC which lets you upload a product image.

Let’s now create code for our UploadProductImage controller method, which the HTML form we have created posts to. This code is shown underneath. Basically in this code we are saving the image back to our server and then updating the existing Product with the image path on our server.

 public ActionResult UploadProductImage(Guid ProductId)
 if (Request.Files.Count > 0)
 if (Request.Files[0].ContentLength > 0)
 HttpPostedFileBase postedFile = Request.Files[0];
 string filename = System.IO.Path.GetFileName(Request.Files[0].FileName);
 string strLocation = HttpContext.Server.MapPath("~/images/products");
 Request.Files[0].SaveAs(strLocation + @"\" + filename.Replace('+', '_'));
 Models.DBProducts products = new Models.DBProducts();
 Models.Product Product = products.GetProduct(ProductId);
 Product.ProductImagePath = @"\images\products\" + filename;
 return RedirectToAction("Edit", new { id = ProductId });
 catch (FormatException ex)
 return Content(ex.Message);
 catch (Exception ex)
 throw ex;
 return RedirectToAction("Edit", new { id = ProductId });

So let me explain the code above. First of all note the method definition. The method accepts a parameter called ProductId which has the same name as our hidden field inside our HTMLform. You will be able to access the file uploaded using the Request.Files property.

On line 4 I am ensuring that there is at least one file and on line 8 I am ensuring that the file uploaded is not empty.

On line 10 I am getting the actual file uploaded as an HttpPostedFileBase class. I am then getting the filename of the file uploaded.

On line 12 I am getting the actual path where the image will be saved on the server. For those of you who do not know the Server.MapPath() basically returns the physical location on the server for a specific path. So for example, in our case we are getting the server physical path of the images/products folder. Remember that we need to transfer the file from the client pc to the server, and therefore we need to find the server physical location where the image will be saved. On line 13 we are then saving the image from the client to the server physical path using the SaveAs method. I am replacing the + sign with an _ since the + sign is not valid in a URL.

Then from line 15 to 17 I am saving the relative image path back to the database. So for example we might be saving /images/products/Image1.jpg back to our database.

On line 18 and on line 30 I am redirecting the user back to the Edit View and redisplaying the Edit Product MVC View. Note that I am passing the id parameter back to the controller. The Product should then be shown together with its new product image.

Finally let me give you part of the code to display an image on an ASP.NET MVC View. This code should be included in the ASP.NET MVC View which displays the product. I am not going to show you all the code which displays all the other Products fields, since this was covered in this blog. Rather I will only be showing the code which displays the image on our ASP.NET MVC View.

@if (!string.IsNullOrEmpty(Model.ProductImagePath))
 <img src="@Model.ProductImagePath" alt="@Model.ProductDescription" title="@Model.ProductDescription" />

In the above code there are some new things which I will explain. Note the IF statement using Razor syntax. Basically what I am doing is that if the Product has no image associated I am not displaying the img tag. Secondly, I am specifying the src of the Image as being the one which the ProductImagePath inside the Products table points to. Note that in these cases we append Razor code using the @ sign.

Run the application and you should end up with the an ASP.NET MVC View which resembles the one in Figure 2.

Figure 2 - Image uploaded and shown in ASP.NET MVC View

Figure 2 -Image uploaded and shown in ASP.NET MVC View

So I hope you found this blog post useful easy to follow. Till next time take care :) .

10 comments on “Uploading Images in ASP.NET MVC

  1. Anjali on said:

    how to show the preview of image in insert view page as soon as we upload the image in Mvc2

  2. admin on said:

    Do a ree redirect to action to the view which shows the view. Pass the image URL into a view bag and then the image URL would be the view bag content.

  3. can you give me the complete code for this example,
    Perform all curd operations using with Database(INserrt Images also)

  4. HASSAN ABOU-GHAYDA on said:

    Mark could you please send the source code for this blog. Thanks


  5. does this code show images when the user reads the list? Could I get your all codes? and maybe with Database. I appreciate your help.

  6. Ins parbo on said:

    Hi, Nice article. I was looking for something like this. Can you please send me your code?

  7. Shamsher Singh on said:

    Very nice article. Can you please send the source code on may email id?

Leave a Reply

Your email address will not be published. Required fields are marked *


HTML tags are not allowed.