Click here to Skip to main content
14,974,167 members
Articles / Web Development / ASP.NET
Posted 17 Jun 2015

Tagged as


11 bookmarked

ASP.NET Multiple File Uploader

Rate me:
Please Sign up or sign in to vote.
4.22/5 (5 votes)
17 Jun 2015CPOL2 min read
Multiple uploader control for ASP.NET applications


This tip tells you how to create a multiple file uploader for ASP.NET with jQuery.


When it comes to uploading different files from different folder locations, existing file uploader can't do that. In this example, we are going to upload multiple files and send email with attachments.

Image 1

Using the Code

Maximum number of files are determined by the web.config value.

<add key="uploadfilcount" value="5" />

File contents are accessed from HttpFileCollectoin on Upload button click.


Hidden fields are used to store Maximum uploading file count, Control Index (Index of new control creating) and Uploaded file count.

<asp:HiddenField ID="hdnMaxFile" runat="server" ClientIDMode="Static" />
<asp:HiddenField ID="hdnCurrentCtrlIndex" Value="0" runat="server" ClientIDMode="Static" />
<asp:HiddenField ID="hdnUploadedFileCount" Value="0" runat="server" ClientIDMode="Static" />

Divs are used for displaying added file information with remove link, total files uploaded and any validation messages.

<div id="dvFileList"></div>
<div id="dvTotalFiles"></div>
<div id="dvMessage"></div>

Some jQuery scripts handle the upload control creation and removal procedure. Basically, the below script creates a new upload control and adds the new file information to the list with file size in kilobytes. I also wired up uploader removal logic as well. When maximum number of files are uploaded, uploader control is set to hidden.

function AddCtlr() {

        var maxFilesCount = $('#hdnMaxFile').val();

        //Add selected file to the list       
        var i = parseInt($('#hdnCurrentCtrlIndex').val());

        var files = $('#fuMultipleFile' + i).get(0).files;
        $("#dvFileList").append("<div class='row' 
        id=filecontainer" + i + ">
	<div class='filename'>" + files[0].name + ' (' + 
	Math.round(files[0].size / 1024) + ' kb)' + 
	"</div> <div class='removelink'><a href='#' 
	onclick=RemoveCtrl(" + i + ");>Remove</a></div>

        //Hide the active control
        $('#fuMultipleFile' + i).attr("style", "display:none");

        // Update uploaded file count
        var uploadedFilesCount = parseInt($('#hdnUploadedFileCount').val());
        uploadedFilesCount = uploadedFilesCount + 1;

        //Display File Count
        DisplayFileCount(uploadedFilesCount, maxFilesCount);

        // Increase the control index
        i = i + 1;

        // Create new control 
        if (uploadedFilesCount != maxFilesCount && uploadedFilesCount < maxFilesCount) {

            $('#dvUploadContainer').append("<div id='dvCtrl" + i + "'>
	<input name='fuCtrl" + i + "'" + " 
	id='fuMultipleFile" + i + "'" + 
	" type='file' onchange='AddCtlr();'></div>");

Below is the file remove logic, if the user clicks the "Remove" link, the corresponding file uploader is removed.

function RemoveCtrl(ctrlindexid) {

    // Remove relevant upload control and added file
    $("#fuMultipleFile" + ctrlindexid + "").remove();
    $("#dvCtrl" + ctrlindexid + "").remove();
    $("#filecontainer" + ctrlindexid + "").remove();

    var i = parseInt($('#hdnCurrentCtrlIndex').val());

    var maxFilesCount = parseInt($('#hdnMaxFile').val());
    var uploadedFilesCount = parseInt($('#hdnUploadedFileCount').val());

    // create new controls
    if (uploadedFilesCount == maxFilesCount) {

        $('#dvUploadContainer').append("<div id='dvCtrl" + i + "'>
<input name='fuCtrl" + i + "'" + " id='fuMultipleFile" + i + "'" +
" type='file' onchange='AddCtlr();'></div>");

    // Update the uploaded file count
    uploadedFilesCount = uploadedFilesCount - 1;

    // Display File Count
    DisplayFileCount(uploadedFilesCount, maxFilesCount);

    // Update the uploaded file count


The below logic displays footer message like "(2 of 5) files are uploaded".

function DisplayFileCount(uploadedFilesCount, maxFilesCount) {
    //Display total files
    $('#dvTotalFiles').append("(" + uploadedFilesCount +
    " of " + maxFilesCount + ")" +
" files are uploaded");

The following logic validates at least a file to be present for uploading.

$('#ibUpload').click(function (e) {

    if ($("#hdnUploadedFileCount").val() == "0") {
        $('#dvMessage').append("Please upload at least one file");

Once the Upload button clicks, uploaded file names and files content (stream) are put in to ArrayList, and process file content to make email attachments and send email. Finally, it redirects to "Thank You" page.

Protected Sub ibUpload_Click(sender As Object, e As EventArgs) Handles ibUpload.Click

    Dim UploadedFileList As HttpFileCollection = fuBankStatements.UploadedFiles

    Dim filenamelist As New ArrayList
    Dim filestreamlist As New ArrayList

    Dim currentFileStream As System.IO.Stream

    For i As Integer = 0 To UploadedFileList.Count - 1

        Dim hpf As HttpPostedFile = UploadedFileList(i)

        If hpf.ContentLength > 0 Then

            currentFileStream = hpf.InputStream

        End If
    Next i

    Me.SendMail(filenamelist, filestreamlist)


    Response.Redirect("Thankyou.aspx", False)

End Sub

The below function reads the ArrayList and turns file contents to attachments. Here, we are not creating any files on disk.

Function SendMail(ByVal attachedFilenameList As ArrayList, ByVal streamList As ArrayList) As Boolean

       Dim message As New MailMessage(ConfigurationManager.AppSettings("FromMail"), _
       message.Body = "Please check attachments"
       message.BodyEncoding = System.Text.Encoding.UTF8
       message.IsBodyHtml = True

       message.Subject = "Test Mail"

       message.SubjectEncoding = System.Text.Encoding.UTF8

       If (attachedFilenameList IsNot Nothing And streamList IsNot Nothing) Then

           If (attachedFilenameList.Count > 0) Then

               For i As Integer = 0 To attachedFilenameList.Count - 1

                   If (attachedFilenameList(i) <> String.Empty And streamList(i) IsNot Nothing) Then
                       Dim emailAttachment As New System.Net.Mail.Attachment(DirectCast(streamList(i), _
           System.IO.Stream), attachedFilenameList(i).ToString())
                   End If


           End If
       End If

       Dim mailClient As New SmtpClient(ConfigurationManager.AppSettings("SMTPServer"))
       Return True

   End Function

Points of Interest

In this example, we haven't added any file types, size validations. If you are using any validations, use client side validations instead of server validations. You can get file information by the following scripts. "fuMultipleFile0" is first upload control and other would be fuMultipleFile1, fuMultipleFile2 and so on.


Image 2


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Chamila Nishantha
Software Developer
Sri Lanka Sri Lanka
No Biography provided

Comments and Discussions

-- There are no messages in this forum --