Click here to Skip to main content
15,884,537 members
Articles / Web Development / HTML
Article

Multiple File Upload User Control

Rate me:
Please Sign up or sign in to vote.
4.69/5 (87 votes)
28 May 2008CPOL5 min read 401.2K   11.4K   219   114
This article describes how to create a file upload user control with events and properties.

MultifileUploadUserControl.gif

Introduction

As we know, an input file element allows you to select only one file at a time, i.e., you can upload only one file at a time using an input file element. If you want to upload multiple files at a time, then you have to add as many file input elements as the number of files you want to upload. The reason behind this is you can only store the file upload information in an input file element. You can not set the value directly for an input file element programmatically, due to security reasons.

Now, I am going to present here an ASP.NET User Control that can be used to upload multiple files at once. I have named it ‘Multiple File Upload User Control’. This doesn’t mean that this user control can upload multiple files using a single file input element. Actually, in this control, an input file element gets hidden after selecting a file, and a new file input element is added in its place. Now, since this phenomenon happens so quickly, it'd seem that there is only one file input element. Hiding a selected file input element and creating a new file input element is done using JavaScript.

Appearance of the User Control

This user control consists of an input file element, a ListBox and three Buttons. A brief description of each is given below:

Description1.png

  • Input file element: Used to select a file.
  • ListBox: Used to display the selected files.
  • Add button: Used to add a selected file into the ListBox.
  • Clear button: Used to remove all selected files from the ListBox.
  • Upload button: Used to upload all the selected files to the server.
  • Delete link: This appears at the right hand side of the each selected file. By clicking on it, you can remove it from selected files list.

Properties of the User Control

This User Control has two public properties.

  • Rows: Used to set/get the number of visible rows to display. The default value for this is 6.
  • UpperLimit: Used to set/get the maximum number of files to upload.

Events of the User Control

This User Control has only one server-side event.

  • Click: Fires when the upload button is clicked. The delegate that represents the Click event signature for the MultipleFileUpload control is given below:
C#
public delegate void MultipleFileUploadClick(object sender, FileCollectionEventArgs e)

I will discuss about it later. The second argument is a FileCollectionEventArgs class that gives useful information about the posted files. This class has following readonly public properties:

  • PostedFiles: Gives the HttpFileCollection of all posted files.
  • Count: Gives the total number of posted files.
  • HasFiles: Gets the value indicating whether this user control contains any posted file or not.
  • TotalSize: Gives the total size in KB of all posted files.

Using the User Control

Drag and drop the user control into an ASPX page and set values for the Rows and UpperLimit properties. The HTML code for this user control looks like:

ASP.NET
<uc1:MultipleFileUpload ID="MultipleFileUpload1" runat="server" UpperLimit="4" Rows="6" />

Next, create an event handler for the Click event for this user control:

C#
protected void MultipleFileUpload1_Click(object sender, FileCollectionEventArgs e)
{
   ...
}

Now, wire up the event handler in the control tag by adding the prefix On in front of the event name. Now, the HTML code will look like:

ASP.NET
<uc1:MultipleFileUpload ID="MultipleFileUpload1" OnClick="MultipleFileUpload1_Click"
                        runat="server" UpperLimit="4" Rows="6" />

Uploading the Posted Files using the User Control

Finally, select the necessary files and click on the Upload button of the user control to upload the posted files. The code for uploading the posted files is given below:

C#
protected void MultipleFileUpload1_Click(object sender, FileCollectionEventArgs e)
{
   HttpFileCollection oHttpFileCollection = e.PostedFiles;
   HttpPostedFile oHttpPostedFile = null;
   if (e.HasFiles)
   {
      for (int n = 0; n < e.Count; n++)
      {
         oHttpPostedFile = oHttpFileCollection[n];
         if (oHttpPostedFile.ContentLength <= 0)
            continue;
         else
            oHttpPostedFile.SaveAs(Server.MapPath("Files") + "\\" + 
               System.IO.Path.GetFileName(oHttpPostedFile.FileName));
      }
   }
}

The above code is straightforward and self-explanatory.

User Control HTML

The HTML of this user control is very simple.

ASP.NET
<asp:Panel ID="pnlParent" runat="server" Width="300px" 
           BorderColor="Black" BorderWidth="1px" BorderStyle="Solid">
   <asp:Panel ID="pnlFiles" runat="server" Width="300px" HorizontalAlign="Left">
      <asp:FileUpload ID="IpFile" runat="server" />
   </asp:Panel>
   <asp:Panel ID="pnlListBox" runat="server" Width="292px" BorderStyle="Inset">
   </asp:Panel>
   <asp:Panel ID="pnlButton" runat="server" Width="300px" HorizontalAlign="Right">
      <input id="btnAdd" onclick="javascript:Add();" 
             style="width: 60px" type="button" runat="server" value="Add"/>
      <input id="btnClear" onclick="javascript:Clear();" 
             style="width: 60px" type="button" value="Clear" runat="server"/>
      <asp:Button ID="btnUpload" OnClientClick="javascript:return DisableTop();" 
           runat="server" Text="Upload" Width="60px" OnClick="btnUpload_Click"/>
      <br />
      <asp:Label ID="lblCaption" runat="server" Font-Bold="True" 
           Font-Names="Verdana" Font-Size="XX-Small" ForeColor="Gray">
      </asp:Label> 
   </asp:Panel>
</asp:Panel>

There are three Panels in this user control. The file panel [ID="pnlFiles"] is for the input file elements, the ListBox panel [ID="pnlListBox"] is for listing the selected files and the Button panel [ID="pnlButton"] has three buttons: two for the client side events and one for the server side. Both the Add button [id="btnAdd"] and the Clear button [id="btnClear"] have client-side onclick events. The server side button [ID="btnUpload"] has a client side OnClientClick event as well as a server side OnClick event. The Label [ID="lblCaption"] is used here to display the upper limit for this user control.

I have used the FileUpload control [ID="IpFile"] of ASP.NET 2.0 in the File panel instead of using an input file element. The reason behind this is it automatically adds enctype="multipart/form-data" to the page's <form> element.

User Control Code

The user control class has following definition for its Click event.:

C#
public event MultipleFileUploadClick Click;

The delegate that represents the Click event signature is given below:

C#
public delegate void MultipleFileUploadClick(object sender, FileCollectionEventArgs e);

FileCollectionEventArgs is an event argument class that contains the basic information about the posted files. I will discuss it later. The Click event for this user control is fired in the click event of the Upload button.

C#
protected void btnUpload_Click(object sender, EventArgs e)
{
   // Fire the event.
   Click(this, new FileCollectionEventArgs(this.Request));
}

The user control class has a private method GetJavaScript(). This method generates the necessary client side JavaScript for this user control. This is registered in Page_Load event of the user control using the RegisterStartupScript method.

Now, let's discuss the FileCollectionEventArgs class that represents the second argument of the Click event.

C#
public class FileCollectionEventArgs : EventArgs
{
    private HttpRequest _HttpRequest;
    public HttpFileCollection PostedFiles
    {
        get
        {
            return _HttpRequest.Files;
        }
    }
    public int Count
    {
        get { return _HttpRequest.Files.Count; }
    }
    public bool HasFiles
    {
        get { return _HttpRequest.Files.Count > 0 ? true : false; }
    }
    public double TotalSize
    {
        get
        {
            double Size = 0D;
            for (int n = 0; n < _HttpRequest.Files.Count; ++n)
            {
                if (_HttpRequest.Files[n].ContentLength < 0)
                    continue;
                else
                    Size += _HttpRequest.Files[n].ContentLength;
            }
            return Math.Round(Size / 1024D, 2);
        }
    }
    public FileCollectionEventArgs(HttpRequest oHttpRequest)
    {
        _HttpRequest = oHttpRequest;
    }
}

The FileCollectionEventArgs class is derived form the EventArgs base class. The constructor for the FileCollectionEventArgs class takes an HttpRequest object as an argument. The FileCollectionEventArgs class has four public properties as discussed earlier. The files property of the HttpRequest class has all the posted files as a HttpFileCollection class. The rest of the properties are easy to understand.

Limitations

The maximum size that can be uploaded to the server using this user control is around 4MB, i.e., the sum of sizes of all the files to be uploaded should be less than 4MB. You can not upload anything that is larger than 4MB. If you want to upload more than 4MB, then you have to make some changes in the web.config file; e.g., if you want to upload around 10MB, then make the following change in the <httpRuntime> node of the system.web section of the web.config file.

XML
<httpRuntime maxRequestLength="102400" executionTimeout="275"/> 

You can find more information regarding this on the MSDN website [^].

Conclusion

I have tried my best to make this user control code error free. I will most welcome suggestions for further improvement in this user control. I have tested this user control on various browsers and it works fine. The list of browsers along with versions is given below:

Browsers.png

License

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


Written By
Technical Lead Infogain India Pvt Ltd
India India


Samir NIGAM is a Microsoft Certified Professional. He is an insightful IT professional with results-driven comprehensive technical skill having rich, hands-on work experience n web-based applications using ASP.NET, C#, AJAX, Web Service, WCF, jQuery, Microsoft Enterprise Library , LINQ, MS Entity Framework, nHibernate, MS SQL Server & SSRS.



He has earned his master degree (MCA) from U.P. Technical University, Lucknow, INDIA, his post graduate dipoma (PGDCA ) from Institute of Engineering and Rural Technology, Allahabad, INDIA and his bachelor degree (BSc - Mathematics) from University of Allahabad, Allahabad, INDIA.



He has good knowledge of Object Oriented Programming, n-Tier Architecture, SOLID Principle, and Algorithm Analysis & Design as well as good command over cross-browser client side programming using JavaScript & jQuery,.



Awards:



Comments and Discussions

 
GeneralRe: I have a Bug Pin
Samir NIGAM29-Apr-08 18:39
Samir NIGAM29-Apr-08 18:39 
GeneralVery nice web application.... Pin
porcupine_tree24-Apr-08 8:25
porcupine_tree24-Apr-08 8:25 
GeneralRe: Very nice web application.... [modified] Pin
Samir NIGAM24-Apr-08 18:56
Samir NIGAM24-Apr-08 18:56 
QuestionHow can I select multi file as yahoo's flick Pin
Dương Nguyễn23-Apr-08 16:28
Dương Nguyễn23-Apr-08 16:28 
AnswerRe: How can I select multi file as yahoo's flick Pin
Samir NIGAM23-Apr-08 18:35
Samir NIGAM23-Apr-08 18:35 
Generalthe same like the one at youconvertit Pin
PeaceTiger22-Apr-08 21:30
PeaceTiger22-Apr-08 21:30 
GeneralRe: the same like the one at youconvertit Pin
Samir NIGAM22-Apr-08 23:40
Samir NIGAM22-Apr-08 23:40 
GeneralBig smiles Pin
quyetthang22-Apr-08 18:26
quyetthang22-Apr-08 18:26 
GeneralRe: Big smiles Pin
Samir NIGAM22-Apr-08 23:38
Samir NIGAM22-Apr-08 23:38 
Answernot good at all Pin
Thanks for all the fish22-Apr-08 7:45
Thanks for all the fish22-Apr-08 7:45 
GeneralRe: not good at all Pin
Samir NIGAM22-Apr-08 18:21
Samir NIGAM22-Apr-08 18:21 
GeneralRe: not good at all Pin
Thanks for all the fish25-Apr-08 9:02
Thanks for all the fish25-Apr-08 9:02 
GeneralRe: not good at all Pin
Samir NIGAM25-Apr-08 18:15
Samir NIGAM25-Apr-08 18:15 
GeneralRe: not good at all Pin
Thanks for all the fish2-May-08 5:11
Thanks for all the fish2-May-08 5:11 
GeneralRe: not good at all Pin
Samir NIGAM2-May-08 18:19
Samir NIGAM2-May-08 18:19 
QuestionHow to increase file upload limit size ? Pin
zakzapakzak20-Apr-08 1:52
zakzapakzak20-Apr-08 1:52 
AnswerRe: How to increase file upload limit size ? Pin
Samir NIGAM20-Apr-08 22:54
Samir NIGAM20-Apr-08 22:54 
GeneralRealy Nice !! Pin
Abhijit Jana16-Apr-08 20:14
professionalAbhijit Jana16-Apr-08 20:14 
GeneralRe: Realy Nice !! Pin
Samir NIGAM17-Apr-08 1:07
Samir NIGAM17-Apr-08 1:07 
QuestionNice work. But how can i pass the uploaded files pathname into the database column.? Pin
zakzapakzak30-Mar-08 20:02
zakzapakzak30-Mar-08 20:02 
AnswerRe: Nice work. But how can i pass the uploaded files pathname into the database column.? [modified] Pin
Samir NIGAM30-Mar-08 23:05
Samir NIGAM30-Mar-08 23:05 
GeneralRe: Nice work. But how can i pass the uploaded files pathname into the database column.? Pin
zakzapakzak31-Mar-08 1:11
zakzapakzak31-Mar-08 1:11 
GeneralRe: Nice work. But how can i pass the uploaded files pathname into the database column.? Pin
Samir NIGAM21-May-08 17:58
Samir NIGAM21-May-08 17:58 
Generalreally good.but one doubt. Pin
abhi4wit25-Mar-08 21:40
abhi4wit25-Mar-08 21:40 
GeneralRe: really good.but one doubt. Pin
Samir NIGAM30-Mar-08 23:13
Samir NIGAM30-Mar-08 23:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.