Create new account I forgot my password    

Upload Multiple Files in ASP.NET using jQuery
Rating: 25 user(s) have rated this article Average rating: 4.4
Posted by: Suprotim Agarwal, on 5/13/2009, in category "jQuery and ASP.NET"
Views: this article has been read 29288 times
Abstract: 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.

Upload Multiple Files in ASP.NET using jQuery
 
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.
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("<b>File: </b>" + hpf.FileName + " <b>Size:</b> " +
                        hpf.ContentLength + " <b>Type:</b> " + hpf.ContentType + " Uploaded Successfully <br/>");
                }
            }
        }
        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("<b>File: </b>" & hpf.FileName & " <b>Size:</b> " & hpf.ContentLength & " <b>Type:</b> " & hpf.ContentType & " Uploaded Successfully <br/>")
                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 Multiple File Upload
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’.
Remove Selected File
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:
Upload Files
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 Some important points to consider while uploading
I hope this article was useful and I thank you for viewing it. The entire source code of this article can be downloaded over here.







Follow me on twitter

Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by anup hosur on Wednesday, May 13, 2009 12:46 AM
Great article.. i am looking for this article.. nothing to do.. Just drag and drop MultiFile.js.. really very nice..
Comment posted by Taru on Thursday, May 14, 2009 3:00 AM
Articles is really very good.Thanks for this articles.
Comment posted by Diego on Thursday, May 14, 2009 8:34 AM
Hi there,

I'm the author of the jQuery plugin mentioned in this article and I'd just like to point out for the record that the project page on the jQuery website:
http://plugins.jquery.com/project/MultiFile/
...is NOT MAINTAINED and NOT UP-TO-DATE.

Whoever wishes to use this plugin should visit the official website:
http://www.fyneworks.com/jquery/multiple-file-upload/

OR the Google Code project page:
http://code.google.com/p/jquery-multifile-plugin/

Ps.: Feel free to delete this comment (as it doesn't add anything to the article) and just update the relevant links.
Comment posted by Suprotim Agarwal on Thursday, May 14, 2009 11:01 PM
Anup, Taru: Thanks for your comments

Diego: Cool plug-in! Keep up the great work. Thanks for the comment about the link. The link has been updated in the article.
Comment posted by Laura on Tuesday, June 02, 2009 12:12 PM
Hello, thank you for the article it solved my problem with uploading multiple images. I don't know if it's a bug or if their is a maximum size of the files to upload, because when i try to upload 2 or more images with the size 2.5 MB each i get an error something like: "The connection was reinitiated while loading the page". If you know how can i resolve this error please tell me. Thank you.
Comment posted by Suprotim Agarwal on Thursday, June 04, 2009 3:00 AM
Laura: In the last para of my article, there is a link 'Some important points to consider while uploading'. Please go throughit
Comment posted by Bruce Browning on Monday, July 20, 2009 4:48 PM
I can get all of the features of this control to work with a webform that does not have a master page.  However, when a master page is present, I am not able to get it to function
Comment posted by Murli on Tuesday, July 21, 2009 2:45 AM
This is realy good article to upload many pages in a single command. i have a query if i don't want to show the list so what i do ?
Comment posted by Mike Johnson on Thursday, July 30, 2009 9:35 PM
I know it's just an example, but please be sure to html encode data you get from the client.
Comment posted by Garima Mishra on Thursday, August 06, 2009 1:45 AM
How can i reflace x to any other remove image?
Comment posted by Wen Ching on Wednesday, August 19, 2009 10:52 AM
Like to check whether this can be done. If I click on browse, then choose a file. Before it is being displayed or allow anyone to upload, I want the file to be scanned first by my antivirus through filescan.aspx without page refresh. Is there a way to achieve this?

Any help? Thanks.
Comment posted by Vinit Sambhare on Wednesday, September 02, 2009 5:02 AM
Hi,
It it very simple and useful functionality. I am looking for this functionality in my application.
Thanks
Vinit
Comment posted by aleem on Wednesday, September 23, 2009 4:37 AM
hi,
this code is not working in master page.My application has a master page i want to use that upload controller in that.
Can you guide me.waiting for ur reply.Thanq...
Regards:
Aleem
Comment posted by Virendra Kumar on Monday, October 05, 2009 4:53 PM
nice article..very easy

thanks
viren
Comment posted by wer on Tuesday, October 06, 2009 4:07 AM
tyrt
Comment posted by Sumesh Babu R on Friday, October 09, 2009 8:01 AM
Very nice article..
Is it possible to restrict the size of each file at client side itself ?
Comment posted by Prem on Wednesday, October 14, 2009 7:07 AM
Bravo...

Cool one...
Comment posted by girish on Wednesday, October 14, 2009 7:13 AM
Chill....
Nice one...
Comment posted by prem on Thursday, October 15, 2009 2:28 AM
we are achieving all the functionality by using only jquery-1.3.2.js and jquery.MultiFile.js
files ,then what is the use of the rest files.Can we discard the rest files
Comment posted by David Jacob Jarquin on Friday, January 08, 2010 10:34 AM
Must of this plugins uses flash and javascript to achieve this (FileReference class to browse files, URLRequest to send the request to upload, all this events can be notify to javascript using ExternalInterface.addCallback, one great plugin using this and jquery is (UPLOADIFY) http://www.uploadify.com/
Comment posted by Ramani Sandeep on Friday, February 05, 2010 4:02 AM
This code does not work if i put the file in folder structure like

  Root/Member/Profile/uploads.aspx

How to resolve this problem.?? Do you have any idea.??

Post your comment
Name:
E-mail: (Will not be displayed)
Comment:
Insert Cancel