Click here to Skip to main content
Licence CPOL
First Posted 26 Mar 2010
Views 112,344
Downloads 7,955
Bookmarked 137 times

Upload Multiple Files in ASP.NET using jQuery

By | 24 May 2010 | Article
Upload Multiple Files in ASP.NET using jQuery

Introduction 

Continuing my ‘no less than an exciting’ journey of exploring ASP.NET with jQuery, today’s article will demonstrate how to Upload multiple files in ASP.NET using jQuery. Fyneworks.com has created a ‘jQuery Multiple File Upload Plugin’. You can download this plug-in here http://www.fyneworks.com/jquery/multiple-file-upload/
As described by the creator of this plug-in, The Multiple File Upload Plugin (jQuery.MultiFile) is a non-obstrusive plugin for the jQuery Javascript library that helps users easily select multiple files for upload quickly and easily whilst also providing some basic validation functionality to help developers idenfity simple errors, without having to submit the form (ie.: upload files).
In this article, I will demonstrate how to use this plug-in with ASP.NET to upload multiple files. We will also display information about the files uploaded – like the name, size and type of the file.
I assume you are familiar with jQuery. If you are new to jQuery, then before moving ahead, I would recommend you to check out Using jQuery with ASP.NET - A Beginner's Guide. Please do take a note that this article uses jQuery’s current version - jQuery 1.3.2 and jQuery 1.3.2 Visual Studio 2008 Autocomplete documentation


Using The Code

Step 1: Open Visual Studio 2008 > File > New > Website > Choose ‘ASP.NET 3.5 website’ from the templates > Choose your language (C# or VB) > Enter the location > Ok. In the Solution Explorer, right click your project > New Folder > rename the folder as ‘Scripts’.
Step 2: Download jQuery 1.3.2 , jQuery VS 2008 Doc and the Multiple File Upload PlugIn. Create a ‘Scripts’ folder in the Solution Explorer of your project and add these files to this folder.
Assuming you have downloaded these files, create a reference to these files in the <head> section of your page as shown below:
<head runat="server">
    <title></title>
        <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
        <script src="Scripts/jquery.MultiFile.js" type="text/javascript"></script>
</head>


Step 3: Now drag and drop an ASP.NET ‘FileUpload’ control from the toolbox to the page. Also add a Button control to the page. This Button control will trigger the upload to the server.
<div>
        <asp:FileUpload ID="FileUpload1" runat="server" class="multi" />
        <br />
        <asp:Button ID="btnUpload" runat="server" Text="Upload All"
            onclick="btnUpload_Click" />
    </div>


Observe that the FileUpload has class=”multi” set on it. This attribute is mandatory.
Step 4: The last step is to add code to upload button. Add the following code:
C# 
protected void  btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            // Get the HttpFileCollection
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0)
                {
                    hpf.SaveAs(Server.MapPath("MyFiles") + "\\" +
                      System.IO.Path.GetFileName(hpf.FileName));
                    Response.Write("File: " + hpf.FileName + " Size: " +
                        hpf.ContentLength + " Type: " + hpf.ContentType + " Uploaded Successfully 
");
                }
            }
        }
        catch (Exception ex)
        {
           
        }
    }
VB.NET 
Protected Sub  btnUpload_Click(ByVal sender As Object, ByVal e As  System.EventArgs) Handles btnUpload.Click
        Try
            ' Get the HttpFileCollection
            Dim hfc As HttpFileCollection = Request.Files
            For i As Integer = 0 To hfc.Count - 1
                Dim hpf As HttpPostedFile = hfc(i)
                If hpf.ContentLength > 0 Then
                    hpf.SaveAs(Server.MapPath("MyFiles") & "\" & System.IO.Path.GetFileName(hpf.FileName))
                    Response.Write("File: " & hpf.FileName & " Size: " & hpf.ContentLength & " Type: " & hpf.ContentType & " Uploaded Successfully 
")
                End If
            Next i
        Catch ex As Exception
 
        End Try
    End Sub
As shown in the code sample above, the ‘HttpFileCollection’ class is used to retrieve all the files that are uploaded. Files are encoded and transmitted in the content body using multipart MIME format with an HTTP Content-Type header. ASP.NET extracts this information from the content body into individual members of an HttpFileCollection.
The ‘HttpPostedFile’ class provides methods and properties to access the contents and properties of each file. In our case, we use this class to check the length, name and type of the file.
That’s it. Click on the ‘Browse’ button to upload a file, one at a time. To upload more than one file, click on the Browse button again and select the file you would like to upload. For demonstration purposes, I have selected five .jpg files.
jQuery_MultipleUpload_1.JPG
If you desire to restrict file types or specify the maximum number of files that can be uploaded, check these examples.
It’s also quite simple to remove a selected file from the list. Just click on the cross ‘x’ to the left of each file. For eg: We will remove DesertLandscape.jpg by clicking on the cross ‘x’.
jQuery_MultipleUpload_2.JPG
Once you have finally decided upon the files to be uploaded, click on the ‘Upload All’ button to upload the files to the server. After the upload, a message will be displayed to the user as shown below: jQuery_MultipleUpload_3.JPG
Note: There could be some issues related to permissions, filesize etc. while uploading files on a server. I have highlighted some issues and their possible solutions in the section.

License

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

About the Author

Gaurav Dudeja India

Software Developer (Senior)
Samsung Electronics
India India

Member

Gaurav Dudeja has done B-Tech from ABES Engg College, Ghaziabad, Uttar Pradesh, India . He is an interested, committed, creative Software professional having more than 3 years of solid experience in web-based and windows based solutions in Microsoft Technologies using .NET 2.0, .NET 3.0 , .NET 3.5, ASP.NET 2.0, ASP.NET 3.5 C# 2.0, AJAX, Web Services, MS SQL Server 2005, WSS (Windows Sharepoint Server 3.0 ). He is also an MCP (Microsoft Certified Professional) and MCTS (Microsoft Certified Technology Specialist) on Web Development (.NET 2.0 ). He has good knowledge of Object Oriented Programming, 3-Tier Architecture and Design Patterns as well as good command over IIS (IIS 5.1,IIS 6.0, IIS 7.0) and deployment of Application on Live Production Environment.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionPlease help me - Upload Multiples‏ limit file size PinmemberGersonbgj10:11 25 May '12  
GeneralMy vote of 3 PinmemberNitin Sawant19:06 4 Apr '12  
GeneralRe: My vote of 3 + 2 PinmemberDewey12:45 9 May '12  
QuestionRetain the selected file list in multifile-list div Pinmembermuthukkumaran Kaliyamoorthy0:25 2 Apr '12  
QuestionThanks Pinmemberr narula19:50 23 Feb '12  
GeneralMy vote of 5 Pinmemberr narula19:50 23 Feb '12  
GeneralMy vote of 4 PinmemberS.M.Naresh19:44 8 Jan '12  
Questiontarget folder anywhere Pinmemberrodchar17:41 23 Dec '11  
QuestionHow can we maintain viewstate in below code Pinmembernitinji2:33 15 Nov '11  
GeneralMy vote of 5 PinmemberSuresh Jat7:45 30 Oct '11  
QuestionFiles bigger than 4MB Pinmemberdavid4life10:15 15 Sep '11  
QuestionIt can't work in Mozilla Firefox... Pinmemberjeepstar35623:41 5 Jul '11  
AnswerRe: It can't work in Mozilla Firefox... PinmemberGaurav Dudeja India23:55 5 Jul '11  
GeneralMy vote of 5 PinmemberShahdat Hosain20:54 29 Jun '11  
QuestionHow to calculate the uploaded file size? Pinmembersantosh.impossible@gmail.com3:09 13 Jun '11  
GeneralProblem with web method PinmemberMember 776123119:28 10 Jun '11  
GeneralRe: Problem with web method PinmemberMember 776123118:36 12 Jun '11  
GeneralProblem Pinmemberjosephchild14:11 8 Jun '11  
GeneralRe: Problem PinmemberGaurav Dudeja India18:13 8 Jun '11  
GeneralRe: Problem Pinmemberjosephchild5:38 9 Jun '11  
GeneralRe: Problem Pinmemberjosephchild7:42 10 Jun '11  
GeneralMy vote of 3 PinmemberMember 44572101:42 4 Jun '11  
GeneralCan you update source at Jquery 1.5? Pinmemberclaudiocas4:40 19 May '11  
GeneralList of files from database Pinmemberkuldeepverma23:23 20 Apr '11  
Generalhelp needed urgently PinmemberMember 776123119:01 12 Apr '11  

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

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 25 May 2010
Article Copyright 2010 by Gaurav Dudeja India
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid