Asp.net MVC File Upload Example

In web application development we often get requirement like uploading file on server from web form, there can be different type of files, here we learn how to upload file on web server in Asp.net MVC application.

asp.net mvc file upload example

File Uploading in Asp.net MVC C#

Here you learn how to upload file in Asp.net MVC web application, I will explain following points with working code.

  • How to upload images / files on asp.net web server
  • How to check file type before uploading
  • Upload other fields in form like name, mobile etc with Image
  • Writing code in MVC Razor and in ActionResult controller
  • Checking if file exists
  • Increase the max upload file size

Asp.net file upload Razor From

Let's design a form in asp.net mvc razor code, place one input control with type="file" and a submit Button in your form. Note: you must specify enctype = "multipart/form-data" in form option

<h3>@ViewBag.ActionMessage</h3>
@using (Html.BeginForm("fileupload","home",
                        FormMethod.Post,
                        new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" id="file" />
    <input type="submit" value="Upload Image" />    
}
Asp.net MVC file upload controller code

now open your controller class and write following two ActionResult, one for Get one with HttpPost

public ActionResult fileupload()
{
return View();
}
[HttpPost]
public ActionResult fileupload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
    {   
    var fileName = Path.GetFileName(file.FileName);
    var userfolderpath = Path.Combine(Server.MapPath("~/userimages/"), fileName);
                            
    file.SaveAs(userfolderpath);
    ViewBag.ActionMessage = "File has been uploaded successfully";
    }
return View();
}
create directory if not exists

In this step you can also create directory if not exists, like in above code we are uploading image files to a folder called “userimages”, assuming folder is there on server.

But good practice would be to put a check, just in case there is no folder with that name then create it

string folderPath = Server.MapPath("~/userimages/");
if (!Directory.Exists(folderPath))
{
    Directory.CreateDirectory(folderPath);
}
Checking if file exists in asp.net mvc

Sometimes you may want to check if the same file is already exists on server, then instead of uploading again you would display a message on user that "Same file already Exists".

[HttpPost]
public ActionResult fileupload(HttpPostedFileBase file)
{
    var fullPath = Server.MapPath("~/userimages/") +  file.FileName;
    if (System.IO.File.Exists(fullPath))
    {
        ViewBag.ActionMessage = "Same File already Exists";
    }
    else
    {
        file.SaveAs(userfolderpath);
        ViewBag.ActionMessage = "File has been uploaded successfully";
    }
      return View();
}
asp.net MVC file upload extension validation

The above code will allow user to upload all type of files. In earlier example we implemented a regular expression control to restrict other file type. But here we check the file type in server side code to make sure only images are allowed, asp.net mvc file upload check file type

public ActionResult fileupload(HttpPostedFileBase file)
{
if (file.ContentType == "image/jpeg" ||
            file.ContentType == "image/jpg" ||
            file.ContentType == "image/gif" ||
            file.ContentType == "image/png")
        {
var fileName = Path.GetFileName(file.FileName);
var userfolderpath = Path.Combine(Server.MapPath("~/userimages/"), fileName);
var fullPath = Server.MapPath("~/userimages/") + "/" + file.FileName;
                    
file.SaveAs(userfolderpath);
ViewBag.ActionMessage = "File has been uploaded successfully";                    
    }
    else
    {
        ViewBag.ActionMessage = "Please upload only imag (jpg,gif,png)";
    }
    return View();
}

You can allow file type as per your business requirement

Asp.net MVC file upload complete code C#

Here is the complete server side code for uploading file in Asp.net C# web application

[HttpPost]
public ActionResult fileupload(HttpPostedFileBase file)
{
string folderPath = Server.MapPath("~/userimages/");
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
if (file != null && file.ContentLength > 0)
    {
        if (file.ContentType == "image/jpeg" ||
            file.ContentType == "image/jpg" ||
            file.ContentType == "image/gif" ||
            file.ContentType == "image/png")
        {
            var fileName = Path.GetFileName(file.FileName);
            var userfolderpath = Path.Combine(Server.MapPath("~/userimages/"), fileName);
            var fullPath = Server.MapPath("~/userimages/") +  file.FileName;
            if (System.IO.File.Exists(fullPath))
            {
                ViewBag.ActionMessage = "Same File already Exists";
            }
            else
            {
                file.SaveAs(userfolderpath);
                ViewBag.ActionMessage = "File has been uploaded successfully";
            }
        }
        else
        {
            ViewBag.ActionMessage = "Please upload only imag (jpg,gif,png)";
        }
    }
    return View();
}
Asp.net MVC file upload with other fields

asp.net mvc file upload with other fields

Sometimes you may have requirement like uploading other fields with image upload, think of situation like student form submission, where student need to provide their name while uploading the picture.

This is how you can design the form.

@using (Html.BeginForm("fileupload",
            "home",
            FormMethod.Post,
            new { enctype = "multipart/form-data" }))
{
<div>Student Name</div>
<input type="text" name="txtPerson" /><br />
<input type="file" name="file" id="file" />
<div style="padding-left:100px;;">
<input type="submit" value="Upload Image" />
</div>
}
    

Now let's look at the controller how to capture all fields' values with the posted file.

[HttpPost]
public ActionResult fileupload(FormCollection form, HttpPostedFileBase file)
{
string _personName = form["txtPerson"];
return View();
}
Increase the max upload file size

Sometimes you may have requirement to increase the upload file size, the setting is in web.config file, The default file size is 4096 (is 4 MB).

<configuration>
<system.web>
<httpRuntime maxRequestLength="4096" />
</system.web>
</configuration>
 
File Upload Code in Asp.net MVC
Aspnet MVC Training
Asp.net MVC tutorials, learn model view controllers with c#, develop database driven web application using Asp.net MVC framework.
Hire .Net Developer
Free Tutorials
ASP.NET MVC Interview Questions Answers
Asp.Net MVC C# Examples | Join Asp.Net MVC Course | Asp.net Core Tutorial