@bobnoordam

MVC File upload

The view part

Our view defines a multipart form to enable us to post both files and other model/form fields. Once a file is uploaded the controller will set the ViewBag.UploadStatus to a confirmation message, causing the upload part to disappear and the confirmation to appear.

  • The multipart declaration in the form is required to be able to post binary data
  • The submit button has a name so we can detect multiple submitbuttons and take appropiate action on submission
  • The input of type FILE displays the file picker button, and the field showing the chosen file.
  • The NAME of the file input defines the uploaded file in the HttpPostedFiles object.
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new {enctype = "multipart/form-data"})) {
    if (string.IsNullOrWhiteSpace(ViewBag.UploadStatus)) {
        <label for="file">Upload file:</label>
        <input type="file" name="file" id="file"/>
        <input type="submit" value="Upload" name="submitButton"/>
        <br>
        <br>
    }
    else {
        <strong>@ViewBag.UploadStatus</strong>
    }
}

The controller part

As you can see the name of the submit button is passed in from the view, and checked. This isnt needed for a minimum setup, but can be very handy if you want to allow the user to upload a file before doing any further validation and processing. This works by setting the name of the upload button to “submitButton” which enables the controller to pick it’s value up in a switch statement or condition.

public ActionResult Index() {
    return View();
}

[HttpPost]
public ActionResult Index(string submitButton, HttpPostedFileBase file) {
    if (submitButton == "Upload") {
        string fileHandle = Server.MapPath("/Cache/") + file.FileName;
        Directory.CreateDirectory(Path.GetDirectoryName(fileHandle));
        file.SaveAs(fileHandle);
        ViewBag.UploadStatus = file.FileName + " uploaded.";
    }
    return View();
}

Security!

This minimum sample allows to upload any and all file of any and all file type. You should validate the upload in the controller and restrict the upload type to what you actualy want users to be able to upload.

Multiple files

You can repeat the upload element as many times as you want. By giving the input elements the same name you will receive an array in the controller that you can loop through. However, this can quickly become tedious for a large number of files because you have to select them all one by one. Using a more advaned uploader like the jQuery uploadiy plugin can present you with a more advanced interface for handling a large number of files.