ASP.NET MVC: Uploading a File

In a project I’m working on, I needed to implement a file upload in ASP.NET MVC. There are basically two ways to implement it:

  1. Handle the upload of the file in the view itself.
  2. Handle it in the controller.

The code for both of them is pretty similar.

First you need to have a file input in your view:

@Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data"})
{
	<input type="file" name="uploadedFile" value="Browse">
	<input id="uploadbutton" type="submit" value="Upload">	
}

If you want to handle it all in the view itself, you can also use null as action and controller name and add the following at the beginning of your view:

@{
    if (IsPost)
    {
        HttpPostedFileBase uploadedFile = Request.Files[0];
        if (uploadedFile != null)
        {
            string fileName = Path.GetFileName(uploadedFile.FileName);
            if (!string.IsNullOrWhiteSpace(fileName))
            {
                string directory = AppDomain.CurrentDomain.BaseDirectory + @"App_Data\UploadedFiles";
                string fileSavePath = directory + "\\" + fileName;
                Directory.CreateDirectory(directory);
                uploadedFile.SaveAs(fileSavePath);
            }
        }
    }
}

In case you want to handle it in the controller, you should provide the right controller name and action name e.g. Index:

@Html.BeginForm("Index", "File", FormMethod.Post, new { enctype = "multipart/form-data"})

Then in your controller create an Index method which will handle the file upload:

public class FileController : Controller
{
    // GET
    public ActionResult Index()
    {
        return View();
    }

    // POST
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase uploadedFile)
    {
        if (uploadedFile != null)
        {
            string fileName = Path.GetFileName(uploadedFile.FileName);
            if (!string.IsNullOrWhiteSpace(fileName))
            {
                string directory = AppDomain.CurrentDomain.BaseDirectory + @"App_Data\UploadedFiles";
                string fileSavePath = directory + "\\" + fileName;
                Directory.CreateDirectory(directory);
                uploadedFile.SaveAs(fileSavePath);
            }
        }
        return RedirectToAction("Index");        
    }
}

That’s it ! If you want to handle multiple file uploads e.g. to allow a user to upload a resume, a motivation letter, a degree… it’s damned easy.

In case you went for the solution in the view, you just have to iterate through Request.Files.

If you went for the solution in the controller, just change the signature of your action to take an enumerable instead of a single HttpPostedFileBase:

public ActionResult Index(IEnumerable<HttpPostedFileBase> uploadedFile)

Then iterate through the enumeration and save each file.

2 thoughts on “ASP.NET MVC: Uploading a File

  1. Thanks for simplifying and explaining how to do file upload from within MVC. I quickly copied the example code and using from within the form, it works. But when I switch to use it as a method within a controller, it is lacking the file handle.
    In the form code you have this: uploadedFile = Request.Files[0]

    My question is how to pass the file handle into the controller method. I thought MVC would automatically map the value in the Browse field to the method when the form is submitted. But all this code does is exit because the file is null.

    Oops. Nevermind. In the Input element I just had to change the name attribute to ‘uploadedFile’ in place of ‘fileUpload’ and then it mapped to the parameter for the controller method.

Leave a Reply

Your email address will not be published.