Multiple File Upload in Asp.Net

February 21st, 2013
Microsoft’s .Net has a come a long way when it comes to uploading various types of files. With Asp.Net version 2.0, it has introduced the “FileUpload” server side control for the very first time. This has virtually simplified the way files are uploaded using Asp.Net.

In this article, we will see with example on how we can upload multiple files using Asp.Net. For this very purpose, we will use Asp.Net FileUpload control with HttpFileCollection class. In addition, we will also check how we can restrict or limit the number files be uploaded, the limit we will set in our example is 10.

Limiting or restricting the number files for upload using Asp.Net has its advantages.

01) It will not put unnecessary burden on the Host server, and save valuable bandwidth.

02) Multiple files can be efficiently uploaded, since all the files can be checked for permissible size, type of files etc, at the server side using code behind procedures.

Multiple File Upload

Recommended for you
Upload Multiple files using JQuery Plugin with Asp.Net

We will check for duplicate files while uploading the files to the server, ignoring the files extension. That is, we will not upload more than one file with the same name, irrespective of the file type.

E.g.: If the first file is “1.jpeg” and uploaded, then “1.pdf” will be considered duplicate and will not be uploaded.

The Asp.Net FileUpload control is a combination of a “Textbox” and a “Button” control. Together they allow us to select file(s) to upload at a remote location. Clicking the button will pop up a “Dialog box” or a “Window”, which will show a list of “Folders” and “Files” in the drive of your local machine. The “Textbox” will show the full path with the selected file(s) name.

By default the “FileUpload” control will allow the users to select only a “single” file at a time. This is how it looks when you first add it to the web page.

<asp:FileUpload ID="fileUpload" runat="server" />

To allow users to select “Multiple” files just add multiple=“true”.

<asp:FileUpload ID="fileUpload" multiple="true" runat="server" />

Finally we will upload the files using Asp.Net HttpFileCollection class. This class will keep an eye on all the files uploaded from client side. There by giving vital information about the file size, type etc. Along with it we will use “System.IO” namespace, which will allow us to check for duplicate files in a particular Folder or Directory on the server.

The Markup
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html>
<head id="Head1" runat="server">
    <title>Multiple File Upload</title>
    
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    
    <style type="text/css">
        #divFile p { font:13px tahoma,arial }
        #divFile h3 { font:16px arial,tahoma; font-weight:bold }
    </style>
</head>

<body>
    <form id="form1" runat="server">
        <div id="divFile">
            <h3>Multiple File Upload in Asp.Net (C#)</h3>
            
            <p><asp:FileUpload ID="fileUpload" multiple="true" runat="server" /></p>
            <p>
                <input type="button" id="btUpload" value="Upload Files" 
                    onserverclick="btUpload_Click" runat="server" />
            </p>
            <p><asp:label id="lblFileList" runat="server"></asp:label></p>
            <p><asp:Label ID="lblUploadStatus" runat="server"></asp:Label></p>
            <p><asp:Label ID="lblFailedStatus" runat="server"></asp:Label></p>
        </div>
    </form>
</body>

<script>
    $('#btUpload').click(function() { 
        if (fileUpload.value.length == 0) { alert('No files selected.'); return false; } 
    });
</script>

</html>
Code Behind (C#)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class _Default : System.Web.UI.Page 
{
    protected void btUpload_Click(object sender, EventArgs e)
    {
        if (fileUpload.HasFile)     // CHECK IF ANY FILE HAS BEEN SELECTED.
        {
            int iUploadedCnt = 0;
            int iFailedCnt = 0;
            HttpFileCollection hfc = Request.Files;
            lblFileList.Text = "Select <b>" + hfc.Count + "</b> file(s)";

            if (hfc.Count <= 10)    // 10 FILES RESTRICTION.
            {
                for (int i = 0; i <= hfc.Count - 1; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    if (hpf.ContentLength > 0)
                    {
                        if (!File.Exists(Server.MapPath("CopyFiles\\") + Path.GetFileName(hpf.FileName)))
                        {
                            DirectoryInfo objDir = new DirectoryInfo(Server.MapPath("CopyFiles\\"));
                            string sFileName = Path.GetFileName(hpf.FileName);
                            string sFileExt = Path.GetExtension(hpf.FileName);

                            // CHECK FOR DUPLICATE FILES.
                            FileInfo[] objFI = objDir.GetFiles(sFileName.Replace(sFileExt, "") + ".*");

                            if (objFI.Length > 0)
                            {
                                // CHECK IF FILE WITH THE SAME NAME EXISTS (IGNORING THE EXTENTIONS).
                                foreach (FileInfo file in objFI)
                                {
                                    string sFileName1 = objFI[0].Name;
                                    string sFileExt1 = Path.GetExtension(objFI[0].Name);

                                    if (sFileName1.Replace(sFileExt1, "") == sFileName.Replace(sFileExt, ""))
                                    {
                                        iFailedCnt += 1;        // NOT ALLOWING DUPLICATE.
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                // SAVE THE FILE IN A FOLDER.
                                hpf.SaveAs(Server.MapPath("CopyFiles\\") + Path.GetFileName(hpf.FileName));
                                iUploadedCnt += 1;
                            }
                        }
                    }
                }
                lblUploadStatus.Text = "<b>" + iUploadedCnt + "</b> file(s) Uploaded.";
                lblFailedStatus.Text = "<b>" + iFailedCnt + "</b> duplicate file(s) could not be uploaded.";
            }
            else lblUploadStatus.Text = "Max. 10 files allowed.";
        }
        else lblUploadStatus.Text = "No files selected.";
    }
}
Vb.Net
Option Explicit On
Imports System.IO

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub btUpload_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) _
            Handles btUpload.ServerClick

        ' CHECK IF ANY FILE HAS BEEN SELECTED.
        If fileUpload.HasFile Then
            Dim iUploadedCnt As Integer = 0
            Dim iFailedCnt As Integer = 0
            Dim hfc As HttpFileCollection = Request.Files

            lblFileList.Text = "Select <b>" & hfc.Count & "</b> file(s)"

            If hfc.Count <= 10 Then             ' 10 FILES RESTRICTION.
                For i As Integer = 0 To hfc.Count - 1
                    Dim hpf As HttpPostedFile = hfc(i)
                    If hpf.ContentLength > 0 Then
                        If Not File.Exists(Server.MapPath("CopyFiles\") & Path.GetFileName(hpf.FileName)) Then

                            Dim objDir As New DirectoryInfo(Server.MapPath("CopyFiles\"))
                            Dim objFI As FileInfo() = objDir.GetFiles(Replace(Path.GetFileName(hpf.FileName), _
                                                      Path.GetExtension(hpf.FileName), "") & ".*")
                            If objFI.Length > 0 Then
                                ' CHECK IF FILE WITH SAME NAME EXISTS (IGNORING THE EXTENTIONS).
                                For Each file As FileInfo In objFI
                                    If Replace(objFI(0).Name, Path.GetExtension(objFI(0).Name), "") = _
                                        Replace(Path.GetFileName(hpf.FileName), Path.GetExtension(hpf.FileName), "") Then

                                        iFailedCnt = iFailedCnt + 1
                                        Exit For
                                    End If
                                Next
                            Else
                                ' SAVE THE FILE IN A FOLDER.
                                hpf.SaveAs(Server.MapPath("CopyFiles\") & Path.GetFileName(hpf.FileName))
                                iUploadedCnt = iUploadedCnt + 1
                            End If
                        End If
                    End If
                Next i
                lblUploadStatus.Text = "<b>" & iUploadedCnt & "</b> file(s) Uploaded."
                lblFailedStatus.Text = "<b>" & iFailedCnt & "</b> duplicate file(s) could not be uploaded."
            Else
                lblUploadStatus.Text = "Max. 10 files allowed."
            End If
        Else
            lblUploadStatus.Text = "No files selected."
        End If
    End Sub
End Class

For single file upload just add the below code in the “Button” click event.

fileUpload.SaveAs(Server.MapPath("CopyFiles\" & fileUpload.FileName))

Note: "CopyFiles\" is the name of the folder at the server, in which the files will uploaded.

comments powered by Disqus

Join our Google Plus Community and be a part of a discussion!