Multiple File Upload Sample Using HttpFileCollectionBase in MVC: Day 39

Let's see the step-by-step implementation:

  1. Create an MVC project from the "Empty" template.

    Right-click on "Controllers" and select "Add" >> "Controller...".

  2. Select "MVC 5 Controller - Empty" to add an empty controller.

    Click on the "Add" button.

  3. Name the controller "HomeController".

    The Index() action result method will be added.

  4. To add a view, right-click on "Index" and select "Add View...".

  5. Name the view and select "Empty (without model)" as the template. Click on the "Add" button.

  6. We use the form attribute with the post method in our cshtml file. Inside the form attribute we have created a file upload and submit button. As our requirement is to upload multiple files, we need to set attribute multiple=multiple with file upload control.

    cshtml file

  7. Here in the HTTP post method, the uploaded file will be available as an HttpPostedFileBase parameter. HttpPostedFileBase serves as the base class for classes that provide access to individual files that have been uploaded by the client. That means we get only one file in this parameter.

    So we use a request object. Using Request.Files we get all the posted files and store them in HttpFileCollectionBase. HttpFileCollectionBase serves as the base class for classes that provide access to files that were uploaded by a client. Once we have a collection of files, we iterate the collection and get each file one by one and assign them to HttpPostedFileBase.

    Using HttpPostedFileBase we can have properties like ContentLength, ContentType, FileName and so on. First we get the physical path of our application using Server.MapPath and then save the file inside the images folder.

    cs code

  8. Now run the project and click on the "Choose File" button. Select the multiple files that you want to upload from your directory structure.

    file upload form

  9. It will show the number of selected files with the "Choose Files" button. Now press the "Upload" button.

    selected files

  10. All the files are uploaded and you can see the files in the browser.

    files are uploaded

  11. We can also check the existence of these files in the images folder.

    images folder
<< File Upload Sample in MVC: Day 38

Similar Articles