Upload Multiple Files in ASP.NET using jQuery

Posted by: Suprotim Agarwal , on 5/13/2009, in Category jQuery and ASP.NET
Views: 202937
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.
Give me a +1 if you think it was a good article. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal




Page copy protected against web site content infringement by Copyscape


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.??
Comment posted by Wayne on Tuesday, February 09, 2010 5:39 PM
Some of these comments are just pathetic, so much for caring about spam.  Thanks for the great overview and examples.  I'm going to take this one for further testing in my current application.
Comment posted by ana on Thursday, February 25, 2010 7:14 AM
Hi, im very new to jquery and doing first time uploading files code in asp.net using jquery.i follow ur code and it runs without error but when i click Uplaod All it doesnt shows images on the page.i m not understanding it.whether i hav to create a Css file to create class for multi.Plz help me where the pictures and files will be saved after uploading.i m not getting it.plz tell me from the very first step.waiting for ur response and thanks in advance.
Comment posted by Ne7ven on Monday, April 05, 2010 11:32 PM
hi, your post is very helpful for me. You don't mind if i ask you a question ?
I'd like to add progress bar to show time uploading while user upload multifiles. Could you show me the way to do it ? thank in advance.
Comment posted by Afzal on Wednesday, April 21, 2010 5:15 AM
Hi,
I want to show image added in thumnail what i have to do.
Please reply.
Comment posted by Afzal on Wednesday, April 21, 2010 6:09 AM
Hi,
I want to show image added in thumnail what i have to do.
Please reply.
Comment posted by Afzal on Wednesday, April 21, 2010 7:49 AM
Hi,
I want to show image added in thumnail what i have to do.
Please reply.
Comment posted by Afzal on Wednesday, April 21, 2010 8:34 AM
Hi,
I want to show image added in thumnail what i have to do.
Please reply.
Comment posted by a on Tuesday, May 11, 2010 9:11 AM
a
Comment posted by joydeep on Friday, May 21, 2010 12:23 AM
its nice plugin ... i have implemented it on my website.. but by any chance u can tell me .... if there are any ways to implement this functionality using multiple file selecction.... this takes d selection one by one ..... i want to implement multiple file select and then when d submit button has been hit it wd upload all... just the multiple selection causes d problem .... can u please tell me a way how to implement that in asp.net ?
Comment posted by Crusader on Monday, June 07, 2010 3:40 AM
hi
Im using this plugin. it works fine for insert mode.
but i want to use this in edit mode also.
How can i do that?
i need to show the already uploaded files in database using this plugin?
Please help me out!!!

Thanks Ahead !!!...
Comment posted by jiss on Tuesday, June 08, 2010 7:27 AM
thanks dude. easy but smartly implemented.
I have used following code to implement remove image and max length and other features. Not sure its correct way or not but its working fine for me :p

<script type="text/javascript">
    $(function() { // wait for document to load
    $('#ctl00_cphBody_FileUpload1').MultiFile({
            
            STRING: {
                remove: '<img src="../images/cancel.png" height="16" width="16" alt="x"/>'
                
            }
        });
    });
</script>

<asp:FileUpload ID="FileUpload1" runat="server" maxlength="5" accept="gif|jpg|txt|doc|zip"   />
Comment posted by Crusader on Wednesday, June 09, 2010 3:54 AM
hi
Im using this plugin. it works fine for insert mode.
but i want to use this in edit mode also.
How can i do that?
i need to show the already uploaded files in database using this plugin?
Please help me out!!! its urgent

Thanks Ahead !!!...
Comment posted by Dhileep on Thursday, June 24, 2010 9:16 AM
hi

Very nice one. But i have one more need. How can i add multiple files in a single click. Thanks in advance.
Comment posted by AHMED ALAHDAL on Saturday, June 26, 2010 4:09 PM
thank you
Comment posted by Arc on Saturday, July 10, 2010 6:10 AM
where is IMPORTANT ISSUE WHILE UPLOADING? nothing is written there
Comment posted by Suprotim Agarwal on Sunday, July 11, 2010 2:14 AM
Check the article http://www.dotnetcurry.com/ShowArticle.aspx?ID=68
Comment posted by Ramonfer on Wednesday, July 14, 2010 3:50 PM
Another Free Fast Multi Site File Uploader:
http://www.multisiteupload.com
You can upload music, video, photos, images, files, pdf, zip... to 12 Hots with only one click in seconds.  
Works well. Recommended.
Comment posted by Verusa Domethildes on Monday, August 09, 2010 9:31 AM
Thank you! Great article!
Comment posted by mehala on Tuesday, August 24, 2010 6:23 AM
tis article s realy 2 gud........
i need the multiple files which s send in windows application form C#....
plz,help me to send the code to my email

Comment posted by Sonika on Friday, August 27, 2010 8:03 AM
Nice article!! Thanx
Comment posted by bach tuot on Monday, August 30, 2010 11:27 AM
I am trying to use your code and ran into a requirement issue.  The way you show only has one file upload control.  What if I need more than one file upload controls in the same page.  I use two file upload controls (each one must contain one or more files); I don't know how to tell which file(s) go with which file upload control in order to store it properly.  Can you shed some light on this?

Thanks alot.
Comment posted by bach tuot on Monday, August 30, 2010 11:38 AM
I am trying to use your code and ran into a requirement issue.  The way you show only has one file upload control.  What if I need more than one file upload controls in the same page.  I use two file upload controls (each one must contain one or more files); I don't know how to tell which file(s) go with which file upload control in order to store it properly.  Can you shed some light on this?

Thanks alot.
Comment posted by Nirvit Jani on Friday, December 17, 2010 12:58 AM
hi,

i want to select multiple files when click on upload using control key.
is it possible with j-query 1.3.2?
if possible then please send me sample or it..

Kindly help me in this regard.
Comment posted by Hardik Patadia on Wednesday, January 12, 2011 11:08 PM
This is simple and very nice example
good one
thnkx
Comment posted by prasad on Monday, January 17, 2011 7:59 PM
Hi,

   it is uploading only one file, if we have to upload only one image, why do we have to use jquery.

  So many people have asked here, why it is not uploading multiple images? can you please explain this.

It will help everyone i believe.
Comment posted by srinivasu dandamudi on Thursday, February 10, 2011 12:47 PM
nice, very userful one
Comment posted by Siwanka on Thursday, March 10, 2011 2:24 AM
Is it possible to add two JQuery File Uploader controls in single aspx page? I can't do this as 2nd one also attached to 1st one... Please help..
Comment posted by Sherwin on Monday, March 28, 2011 3:26 AM
Is it possible to check if the current file is existed and overwrite ?
Comment posted by Lakshmanan M on Friday, May 06, 2011 8:01 AM
Its work fine in firefox but not good in ie 6.0 and also needs to check if the file already exist
Comment posted by nishantace on Wednesday, May 11, 2011 5:51 AM
Nice Article, but strange enough found the same on http://www.codeproject.com/KB/aspnet/multiple_file_upload.aspx under different author's name???
Comment posted by the coder on Tuesday, June 14, 2011 9:19 AM
I LOVE YOU MAN I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU I LOVE YOU
Comment posted by Santosh Kumar Patro on Friday, July 08, 2011 5:11 AM
Hi Suprotim,

Thanks a lot for your article. It helped me a lot to learn regarding upload files using Jquery. But I have one doubt regarding how to calculate the size and display it adjacent to the file name.

Please help me to calculate the file size and display it adjacent to the file name.

Thanks In Advance,

Thanks & Regards,
Santosh
Comment posted by Ahmed Almansouri on Tuesday, October 25, 2011 7:02 AM
Big thanks for the Author and all who comment a useful comments :D
Comment posted by Abdhesh Kumar Mishra on Monday, November 21, 2011 12:33 AM
How we can change image size during upload file.

How we can get height and width of every image.

i need urgent help

Regards

Abdhesh Mishra
9999208994
Comment posted by Chaitanya on Tuesday, January 10, 2012 5:18 AM
Hi I need small help i.e when I am using drop down and it's autopostback property is set to true. When I select some files and access an item in drop down the files are getting cleared what should I do in order to view the files
Comment posted by Sophia on Saturday, January 21, 2012 4:29 AM
HI,
I copied the code to my page, it is not uploading the files to the specified folder. The code breaks at
if (hpf.ContentLength > 0)
in the for loop.

kindly tell me what could be the problem?
Thanks
Comment posted by Y.J.Bejan Dhas on Sunday, January 22, 2012 11:04 PM
HI
I am an final year student. Can u help to know how to upload and download different file formats in an sqlserver using dotnet.
Comment posted by Tony on Thursday, February 09, 2012 11:25 AM
Nice one! Thanks. By the way, you can do all of the file handling server-side: checking for duplicates, renaming etc
Comment posted by Kartar Bidhuri on Tuesday, May 08, 2012 9:31 AM
Hi ,
I have some requirement of multiple file upload with the condition that i can not call button postback method.
So i want to call webservice method using jquery on upload button click and when i get
HttpFileCollection hfc = Request.Files;
in my service method file count is 0 . Please suggest how can i get attached files with webservice call. I can not write server side click for button.
Waiting for your reply. please reply asap.
Thanks!!
Kartar
Comment posted by wantknow on Thursday, July 12, 2012 3:42 AM
Karter Bidhuri

If you have script manager, Add this in your form load
ScriptManager.GetCurrent(Me).RegisterPostBackControl(btUpload)
Comment posted by abc on Friday, July 27, 2012 6:02 AM
if I want to shoe the image along with image name and cross sign, what should I do
Comment posted by Nurlan on Sunday, July 29, 2012 10:16 AM
I couldn't upload files with big sizes (totally more than 4 MB), how to avoid this restriction?
Comment posted by Nurlan on Sunday, July 29, 2012 10:30 AM
I couldn't upload files with big sizes (totally more than 4 MB), how to avoid this restriction?
Comment posted by Suprotim Agarwal on Monday, July 30, 2012 5:12 AM
You can change the maximum file size by changing the maxRequestLength attribute of the httpRuntime element in the web.config file. You can also increase the ‘executionTimeout’. By default it is 110 seconds
Comment posted by A on Thursday, August 02, 2012 9:24 AM
some dude on codeproject copied your article
Comment posted by Pavan on Saturday, August 18, 2012 8:56 AM
Hi,
The solution works on local machine perfectly. When deployed on hosting server godaddy (medium trust) it is allowing to upload only one image. If we try to upload next image the first one is getting replaced. Even it is not showing the uploaded file with delete button below the fileupload control.
Can I say this is a concern regarding trust level.?
Any suggestions?
Comment posted by Jose on Wednesday, August 22, 2012 2:03 PM
Excellent article! Well explained!

Thanks!
Comment posted by Joe on Wednesday, August 22, 2012 2:22 PM
Hi,

Is there any reason why the "upload successfully" is being displayed twice for every file?

I have checked hfc.count and it comes back with the correct number of files. Any ideas?


Thanks,
Joe
Comment posted by Shyam on Thursday, November 01, 2012 5:43 AM
Hi,
How to check file size and give alert/warning message when file is brows from FileUpload control as we were checking for file Type.
Comment posted by mantu on Monday, November 05, 2012 9:19 AM
thanks
Comment posted by Hemanth on Thursday, November 15, 2012 1:01 AM
Thanks Its Very Help Full For Me But it is not working fine in Internet Explorer When Ever i Uploaded images it uploaded only 2 images but it working fine in Mozilla Firefox And Google Chrome Please Help Me what ever you Wrote Above Code Same I copied And Pasted.
Comment posted by NandaKishor G N on Monday, January 21, 2013 5:38 AM
Thanks for the Article.But, It is not working in Google chrome...please suggest the code change...
Comment posted by Md Saleha on Thursday, February 21, 2013 6:35 AM
here is the easiest way...in the world...after lots of frustration..finally
upload with using any plug-in...

Filename.aspx.cs

protected void btnupload_Click(object sender, EventArgs e)
    {
       string tempPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
       string savepath = Server.MapPath(tempPath);
        for(int i=0;i<Request.Files.Count;i++)
        {            
            HttpPostedFile hpf = Request.Files[i];
            string filename = hpf.FileName;
            hpf.SaveAs(savepath + @"\" + filename);
        }

    }

Filename.aspx

<div>
        <input type="file" id="FileUpload1" multiple="multiple" runat="server"/>
        <asp:Button runat="server" ID="btnupload" Text="Upload"
            onclick="btnupload_Click"/>&nbsp;<br/>
        <asp:Label runat="server" ID="Label1"></asp:Label>

    </div>

Web.config

<appSettings>
    <add key ="FolderPath" value ="uploads"/>
</appSettings >

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