Multiple File Upload Sample Using HttpFileCollectionBase in MVC

Multiple File Upload Sample Using HttpFileCollectionBase in MVC

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

Create an MVC project from the "Empty" template.

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

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

Click on the "Add" button.

Name the controller "HomeController".

The Index() action result method will be added.

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

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

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.

1.jpg

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.

2.jpg

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

3.jpg

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

4.jpg

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

5.jpg

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

6.jpg