CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
How to Upload Multiple Files in ASP.Net?

By Bala Murugan
Posted On Nov 04, 2010
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 5
Category: ASP.Net
Print this article.

How to Upload Multiple Files in ASP.Net?

Uploading files is one of the frequently done tasks when developing asp.net websites. We normally use FileUpload control available in asp.net control set to do this task. The limitation of using FileUpload control is we can upload only one file at a time. At times, we may have requirements to provide a feature where users can upload multiple files at a time. The easy way of implementing this is by placing more than one FileUpload control in a page. But, when doing in this way, we need to know the number files the user will be uploading so that as many FileUpload control can be placed in the page.

Moving forward, we will see how to develop a feature which can provide the capability to upload multiple files without having any restriction on number of files. In order to this, we develop a feature where user can add as many as FileUpload control by clicking a link called “Add file..”. 

Refer the below figure,

Multiple File Upload in ASP.Net and C#

To add more file upload control, user has to click “Add file..” link which will add another control to the control list. We will use jQuery library to do the client side interaction in this article.

Doing Multiple File Uploads in ASP.Net

Steps

1.      Create a new Asp.Net project using your Visual Studio 2008 IDE with the language of your choice.

2.      If you are new to jquery, read the following Faq’s to integrate jQuery library into your project.

What is jQuery? How to use it in ASP.Net Pages?

How to enable jQuery intellisense in Visual Studio 2008?

How to use jQuery intellisense in an external javascript file?

3.      Create a folder in server and provide appropriate permission (Read, Write & Modify)to the ASP.Net service account in order to save the uploaded files. Configure this folder in AppSettings of the project so that it can be accessed from code.

4.      Drag a Button control from visual studio toolbox to upload the files to server. Also, drag a Label control to display success/failure message.

5.      Now, with the help of jQuery library we will provide a way to add as many file upload control in the page. Refer the code below,

ASPX

<script type="text/javascript" src="_scripts/jquery-1.4.1.min.js"></script>

<script type="text/javascript">

        var i = 1;

        $(document).ready(function() {

            $("#addfile").click(function() {

                $("#dvfiles").append("<input name="+i+"fu type=file /><br>");

       i++;

            });

        });      

</script>

</head>

<body>

<form id="form1" runat="server" enctype="multipart/form-data">

<div id="dvfiles">

 

</div>

<a href="#" id="addfile">Add file..</a><br />

<asp:Label ID="lblMessage" runat="server"></asp:Label><br />

<asp:Button ID="btnUpload" runat="server" Text="Upload"

        onclick="btnUpload_Click" />

</form>

 

Codebehind

protected void btnUpload_Click(object sender, EventArgs e)

    {

        try

        {

            HttpFileCollection filecolln = Request.Files;           

            for (int i = 0; i < filecolln.Count; i++)           

            {

                HttpPostedFile file = filecolln[i];

                if (file.ContentLength > 0)

                {

                    file.SaveAs(ConfigurationManager.AppSettings["FilePath"] + System.IO.Path.GetFileName(file.FileName));                 

                }

            }

            lblMessage.Text = "Uploaded Successfully!";

 

        }

        catch (Exception ex)

        {

            lblMessage.Text = ex.Message;

        }

    }

 

The above code will populate the file upload control in the div tag (dvfiles) whenever addfile hyperlink is clicked.

Note

Please note the enctype attribute in the form tag above. If you use ASP.Net FileUpload control, this attribute will be populated automatically in form tag. But, here we need to specify this attribute explicitly since we are populating the file upload (HTML file control) controls ourselves from client side. Without setting this attribute, the file upload will not work.

6.      It's done! Execute and see it in action.

 




Validating the empty file upload control and provide remove functionality

It will be good and user friendly if we validate the empty file upload control and let the users know that some of the file upload controls are empty when Upload button is clicked.

Something like below,

Multiple File Upload in ASP.Net and C#

In the above figure, the empty file upload controls are highlighted in red when Upload is clicked. This will indicate the users to select the files in those controls. Users can click the remove link adjacent to file upload control to remove the control.

The below jQuery code can be used to do that,

<script type="text/javascript" src="_scripts/jquery-1.4.1.min.js"></script>

<script type="text/javascript">

        var i = 1;

        $(document).ready(function() {

            $("#addfile").click(function() {

                $("#dvfiles").append("<input name=" + i + "fu type=file /><a href=#>remove</a><br>");

                i++;

            });

 

            $("#dvfiles a").live('click', function() {              

                $(this).prev("input[type=file]").remove();

                $(this).remove();

            });

        });

 

        $(document).submit(function() {

            var flag = true;

            $("#dvfiles input[type=file]").each(function() {

                if ($(this).val() == "") {

                    $(this).css("background", "Red");

                    flag = false;

                }

            });

            return flag;

        });       

</script>

 

We are done now. Execute the application and see it in action!

Remember, in the above samples I have not done any validations on file type(basically extension), file size, etc since this article concentrates on multiple file uploads techniques. Keep in my mind that any production code should have these validations in place to prevent any misuse. The below links may help you for the same,

File Size Validation in FileUpload control in ASP.Net

Validate For Invalid File Path in ASP.Net FileUpload control

How to make FileUpload control in ASP.Net 2.0 to Read-Only?

Clearing ASP.Net FileUpload Control in Javascript

Also, doing multiple file uploads will have performance degradation since it deals with large binary data. For this, ASP.Net itself has some restriction on file upload size in place. By default, it allows up to 4 MB of files to be uploaded. Read below,

How to increase default File Upload size in ASP.Net ?

You have to change the settings discussed in the above link appropriately for larger files.

Downloads

Download source

Conclusion

Thus, we have understood how to do multiple file uploads in ASP.Net. Download the code and see it in action. In coming days, we will see how to do multiple file uploads with more modern UI like a GMAIL file upload system. Thanks for reading this article.

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
fg
fghfg
Good One
Good article, Thanks
Small patch :)
Hi!

Good work, but needs a little fix :)

I have change this section a javascript:
$("#dvfiles a").live('click', function() {
$(this).prev("input[type=file]").remove();
$(this).next("br").remove();
$(this).remove();
});
got ERROR when used like usercontrol
hi,
I have created a user control of fileupload
but at this like it is redirecting wrong.
<a href="#" id="addfile">Add file..</a><br />

how to used as a user control please help.
upload Multiple File In ASP.net
this is the very Use Full For New Developer