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 file uploading process.

Here in this article we will show you how to upload “Multiple” files using the “FileUpload” control along with the “HttpFileCollection” class. We will also restrict the number of files to be uploaded at one time, to 10.

Note: Restricting file size has an advantage. It will not put unnecessary burden on the Host server and multiple files can be efficiently uploaded.

Multiple File Upload

Also 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 1 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 the users to select “Multiple” files just add multiple=“true”.

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

Finally to upload these files we will use Asp.Net HttpFileCollection class. This class will keep an eye on all the files upload 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.

Complete Source (Default.aspx.cs)
<%@ 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>
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 thefiles will uploaded.

advertise here
comments powered by Disqus

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