ASP.Net MVC file upload

How to upload file or image in asp.net mvc is not difficult but is totally different compare to asp.net FileUpload control. If we are asp.net developer and we are new to mvc then we immediately noticed we don’t have server side controls so the FileUpload control as well and our problem start here. Now we start searching how to upload a file if there is no FileUpload control, no problem whatever your background is, in this article we will see how to upload a file in mvc without using FileUpload control.

When we use FileUpload control in asp.net web forms it renders htpm input control, here is the rendered HTML for FileUpload control

 <input id="FileUpload1" type="file" name="FileUpload1">

Now we will see the HTML needed to upload a file in mvc, first normal HTML and then razor one

<form action="/UploadPhoto" enctype="multipart/form-data" method="post"> 
    <input id="file" type="file" name="file" style="font-size:14px;" /> 
    <input type="submit" value="Upload" class="btn" />
    <div class="err" style="padding-top:7px;"> 
        @ViewBag.error
    </div>
</form>

OR razor

@using (Html.BeginForm("UploadPhoto", "Home", FormMethod.Post, 
                                       new { enctype = "multipart/form-data" }))
{
    <input id="file" type="file" name="file" style="font-size:14px;" />
    <input type="submit" value="Upload" class="btn" />  
    <div class="err" style="padding-top:7px;"> 
        @ViewBag.error
    </div>      
}

We completed our HTML part and here is the output file upload control design output

So far so good, our design is working as we want, now time to write the controller and business logic to save the file

Here is the home controller code:

[HttpGet]
public ActionResult UploadPhoto()
{
     return View();
}

[HttpPost]
public ActionResult ChangePhoto(HttpPostedFileBase file)
{
  if (file != null && file.ContentLength > 0)
  {
     String FileExtn = System.IO.Path.GetExtension(file.FileName).ToLower();
     if (!(FileExtn == ".jpg" || FileExtn == ".png" || FileExtn == ".gif"))
     {
         ViewBag.error = "Only jpg, gif and png files are allowed!";
     }
     else
     {
       // add name space System.Drawing
       using (Image Img = Image.FromStream(file.InputStream))
       {
          String imgPath = String.Format("UserImages/{0}{1}", Img.FileName, FileExtn);
          Img.Save(String.Format("{0}{1}", Server.MapPath("~"), imgPath), Img.RawFormat);
          // you can add code here to save information to database.
          return View();
        }
     }
    return View();
}

That's all we need to upload a file in mvc, if you want to resize the image and upload in different sizes then see Hamden's article Upload multiple image in multiple size with progress bar in asp.net specially NewImageSize method, I used this and it works well. In my next post I will write about hot to upload multiple files in mvc, hope it will come soon.

Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • mvc
  • asp.net
  • file-upload
By Ali Adravi On 25 May, 13  Viewed: 7,264

Other blogs you may like

mvc search page example with code

MVC Searh page with pagination: It’s very easy to create a search page in asp.net but when I try to create the same in MVC I faced many problems, how to create model, how to keep searched values in search controls, pagination, I found myself nowhere, so start searching for some good examples but... By Ali Adravi   On 25 Aug 2013  Viewed: 34,840

MVC insert update delete and select records

CRUD (Create, Retrieve, Update and Delete) in MVC. When we start to learn new language, first we try to run an application with “Hello World” and then CRUD functionality. So in this article we will see how to select records from database (with WebGrid, pagination and sort functionality), update a... By Ali Adravi   On 17 Aug 2013  Viewed: 96,842

How to create a single thanks page for entire controller in MVC

Sometimes we need a thanks page say we have user registration, change password, activate account functionality in our application then we need a thanks page after registering with our site, to say thanks for registering with us or showing confirmation that your password is successfully changed or... By Hamden   On 30 Jun 2013  Viewed: 3,067

MVC jquery autocomplete with value and text field

In MVC, autocomplete with jquery is the best way to pull data from database and render according to our requirements, so in this article we will use jquery to show the auto complete text box without any ajax controls. We need a method to get the data from database, a controller method to handle the... By Ali Adravi   On 29 Jun 2013  Viewed: 6,010

Upload files with model data in MVC

Upload multiple files with model data in MVC is really very easy, when I started to test by uploading some files, I though it would be more complicated but it is really not. In my previous post [ASP.Net MVC file upload][1], I promised to post soon about how to upload multiple files. When I was... By Ali Adravi   On 04 Jun 2013  Viewed: 22,347