CodeSnip: Uploading Multiple Files At Once
page 2 of 4
by Haissam Abdul Malak
Feedback
Average Rating: 
Views (Total / Last 10 Days): 36718/ 108

Starting to Code

The controls being used are

1.    One HtmlInputFile control

2.    A button to add the file to the list box

3.    A list box control to show the user his selected files

4.    A delete button to remove a previously selected file

5.    A button to save the files into the specific directory

The below listing will show how the HTML code will look after we have added the controls into our WebForm.

Listing 1

<INPUT style="Z-INDEX: 101; LEFT: 83px;
 WIDTH: 489px; POSITION: absolute; TOP: 67px; HEIGHT: 22px" type="file"
 runat="server" id="FileUpload" size="62">
<asp:Button id="Button1"
 style="Z-INDEX: 102; LEFT: 591px; POSITION: absolute; TOP: 66px"
 runat="server" Text="Attach"></asp:Button>
<asp:ListBox id="ListBox1"
 style="Z-INDEX: 103; LEFT: 84px; POSITION: absolute; TOP: 104px"
 runat="server" Height="93px" Width="565px"></asp:ListBox>
<asp:Button id="Button2"
 style="Z-INDEX: 104; LEFT: 339px; POSITION: absolute; TOP: 205px"
 runat="server" Text="Upload"></asp:Button>
<asp:Button id="Button3"
 style="Z-INDEX: 105; LEFT: 684px; POSITION: absolute; TOP: 131px"
 runat="server" Text="Delete" Width="70px"></asp:Button>

Figure 1

 

 

Code behind (C#)

In this section, we will see how each button click event is handled to provide the correct behavior.

Listing 2

private void btnAttach_Click(object sender, System.EventArgs e)
{
  // Save the attached file to fileName variable
  string fileName = FileUpload.PostedFile.FileName;
 
  // If the counter is null then create one with default value equal to 0
  if (ViewState["i"] == null)
  {
    ViewState["i"= 0;
  }
  // Check if a file is selected
  if (fileName != null || fileName != string.Empty)
  {
    // Add it to the collection
    ListBox1.Items.Add(FileUpload.PostedFile.FileName);
 
    // Save an index for each selected file
    int i = Convert.ToInt32(ViewState["i"]);
 
    // Save the fileupload control into a different session
    Session["myupload" + i] = FileUpload;
 
    // Increment the counter
    i++;
 
    // Set the ViewSate to the latest counter value.
    ViewState["i"= i;
 
  }
}

In the above listing, we are handling the Attach button click event. First, we will get the selected file name. We used the ViewState to save the counter (how many files selected). If a file has been selected, we will save its filename as a new Item in the ListBox control, then save its instance in the session state. In the final two lines of code, we are updating the counter value and resaving it in ViewState.

Figure 2

 

The figure above is showing the process that we just explained. Each selected item is being added to the ListBox control.

Listing 3

private void btnDelete_Click(object sender, System.EventArgs e)
{
  if (ListBox1.SelectedIndex >  - 1)
  {
    int uploadedFileIndex = ListBox1.SelectedIndex;
    Session.Remove("myupload" + uploadedFileIndex);
    ListBox1.Items.Remove(ListBox1.SelectedValue);
  }
}     

In the above listing, we are handling the delete button click event. First we are checking if an item in the ListBox control is being selected. We are saving the selected index into a variable, setting its specific information in the session state to null, and finally it gets removed from the ListBox Items collection.

Figure 3

The above figure is showing the ListBox control after we have selected the second item and pressed the delete button.

Listing 4

private void btnUpload_Click(object sender, System.EventArgs e)
{
  int sessionCount = Session.Count
 
  for (int i = sessionCount - 1; i >= 0; i--)
  {
    if (sessionCount <= 3)
    {
      HtmlInputFile hif = (HtmlInputFile)Session["myupload" + i];
      if (hif.PostedFile.ContentLength <= 500000)
      {
        string storePath = Server.MapPath("~"+ "/MultipleUpload";
        if (!Directory.Exists(storePath))
          Directory.CreateDirectory(storePath);
        hif.PostedFile.SaveAs(storePath + "/" + Path.GetFileName
          (hif.PostedFile.FileName));
        Label1.Text = "Your Files are uploaded successfully";
        ListBox1.Items.Clear();
      }
      else
        Label1.Text = "An error occured";
    }
    else
      Label1.Text =
        "You have exceeded the maximum number of files to be uploaded (3)";
 
  }
  Session.RemoveAll();
}

The last stage in our code behind is the upload click event. As you can see, the first thing to do is to get the number of the session variables. Because all the selected files are being saved inside session variables, we will loop through all of the sessions to upload its specified file. Note that we are creating a new folder called MultipleUpload where all the files are being saved on the web server. Do not forget to give the write permission for ASPNET user to avoid the access is denied error. After the files have been uploaded, a message will be displayed to inform the user about the upload status. Finally we clear all the items in the ListBox and the session variables.

Figure 4

The above figure is showing the final stage when the files have been successfully uploaded.

Remember to modify the <httpRuntime maxRequestLength="10000"/> in the web.config to be able to upload files which their size exceeds 4MB. The maxRequestLength value is in KB. In this case, we have modified it to accept the maximum size of 10 MB.


View Entire Article

User Comments

Title: not working   
Name: shekar
Date: 2012-09-28 3:08:59 AM
Comment:
it is not possible for select two or three files at a time..

it is working on only files or images

but not working on songs....
Title: HtmlInputFile is not working   
Name: devjunior
Date: 2012-07-20 2:17:52 AM
Comment:
I always got this error..
'System.Web.UI.WebControls.FileUpload' is a 'type' but is used like a 'variable'
Title: not working   
Name: devjunior
Date: 2012-07-20 2:16:34 AM
Comment:
It doesn't work
Title: Very nice article   
Name: prathyusha
Date: 2012-02-01 3:23:09 PM
Comment:
It's very useful for me
Thanks a lot
Title: Thanx a lot :)   
Name: Arif Prime
Date: 2011-04-08 12:54:57 AM
Comment:
Thank you very much.
This article helped me a lot.
Regard
Haissam Abdul Malak Sir.
My Quote:
"Never thing that WHAT YOU ARE???
You always thing this that WHAT YOU CAN DO."
Title: Very nice and Thank you   
Name: Lavakumar
Date: 2011-03-31 8:55:33 AM
Comment:
Hi Haissam,
It helps me a lot :-). Thank you very much
Title: very nice ..keep the good work up   
Name: nwebsolution
Date: 2010-11-03 11:14:59 AM
Comment:
thank you such nice information.
Title: Upload Multiple image   
Name: suresh
Date: 2010-09-09 12:42:14 AM
Comment:
nice
Title: Upload Multiple image   
Name: Phuc Hoang
Date: 2010-08-27 11:38:54 PM
Comment:
hello everybody

It is very lucky for me to search and find out, how can upload multiple image at once times,
The link http://ajaxuploader.com/Demo/select-multiple-files-upload.aspx is very great
How can i get the code con that page
Thanks in advance
Phuc Hoang
Title: Thanks   
Name: Pandu
Date: 2010-01-25 7:24:40 AM
Comment:
Thanks for providing me the above snippet as i was trying for that and thats very good regarding me Thanks again
Title: Delete Problem   
Name: Juliane
Date: 2009-10-09 7:27:50 AM
Comment:
If I delete a file from the list with the delete button and then upload the remaining, it produces an error. I think someone mentioned this before. Has anyone found a solution?
Thanks.


Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 88: {
Line 89: HtmlInputFile hif = (HtmlInputFile)Session["myupload" + i];
Line 90: if(hif.PostedFile.ContentLength <= 500000)
Line 91: {
Line 92: string storePath = Server.MapPath("~") + "/MultipleUpload";
Title: size files problem   
Name: Cristian
Date: 2009-10-07 10:22:39 AM
Comment:
Hi, excelent post!, i have a q.

if i have configured the maxRequestLength to allow file of 2 mb. i will be able to upload any file with 2 mb maximum.

I'm trying to do an page to upload 12 files at the same time, when i submit the page.

here ther problem is that if each file = 1 mb. it doen't work.

is there any solutions for this case?

Note: the page is an special of image explorer, and i need to upload from 1 to 12 files at the same time,

Thanks in advance

Cristian.-
Title: Selecting Multiple files to upload   
Name: Sarala
Date: 2009-06-11 12:51:24 AM
Comment:
I need the source code
Title: Error in VB.net Code   
Name: Prasad
Date: 2009-02-09 6:38:35 AM
Comment:
I get error when code is converted into VB.NEt

'Save the fileupload control into a different session
Session("myupload" + i) = FileUpload

Pls Help!
Title: Select multiple files for upload control -- ajaxuploader   
Name: ikan
Date: 2008-11-14 1:32:45 AM
Comment:
http://ajaxuploader.com/Demo/select-multiple-files-upload.aspx

this is very nice, can i have the source code?
Title: Select multiple files for upload control -- ajaxuploader   
Name: devore
Date: 2008-09-24 6:49:57 AM
Comment:
http://ajaxuploader.com/Demo/select-multiple-files-upload.aspx
Title: Excellent code for attaching multiple files   
Name: Mohammad Javed
Date: 2008-07-14 8:00:52 AM
Comment:
very nice code for attaching multiple files in a single module.
Title: how do you download the files now?   
Name: jack
Date: 2008-04-16 6:33:21 AM
Comment:
Hi,

nice article on uploading multiple.

But how do i download each uploaded files in vwd2005,c#.

thanks.

jack.
Title: Delete issues   
Name: NoName
Date: 2008-03-05 8:30:27 AM
Comment:
If you attach more than one file, and then delete the first file it crashes. Hmm...
Title: Good   
Name: Bhakti
Date: 2007-12-20 5:07:54 AM
Comment:
this is very good link to upload multiple files at the sane time.Thnak you.
Title: Great work   
Name: Sara
Date: 2007-12-14 7:09:04 AM
Comment:
this is exactlt what i wanted to implement thank you ...
Title: Good!   
Name: SARA
Date: 2007-11-27 2:25:14 AM
Comment:
This CONTENT is very useful for me.
Title: Good.........!   
Name: VirenDRa
Date: 2007-08-10 6:22:08 AM
Comment:
Nice Trick...
Title: How u say this?   
Name: Deepak Vasudevan
Date: 2007-06-19 11:25:42 AM
Comment:
I am sorry, but this is bad example and bad coding practices are illustrated. And you will not be uploading them multiple at once time, neither.
Title: Error   
Name: Edmundo Couto
Date: 2007-06-05 6:27:35 AM
Comment:
Hi Haissam

I was trying to implement your solution in my application, but when i click in the "upload" button it occurs an error.

"Object reference not set to an instance of an object". This error is associated with the line 93:"if (hif.PostedFile.ContentLength <= 500000)".Can you help me with that?

Thanks
Title: THANY YOU   
Name: Tommy
Date: 2007-06-03 5:04:36 PM
Comment:
The solution works.
I just want to thank you for all the help .We need more guys like you around here .It is sad that some members don't give u little creadit that you take the time to answer all the questions, instead they make negative remarks about this article.
Thanks again Tommy
Title: System.IO   
Name: Haissam Abdul Malak
Date: 2007-06-03 4:43:37 AM
Comment:
Hello tommy sorry i forgot to mention that the Path class is under System.IO namespace.
so try System.IO.Path.GetFileName
Title: Error   
Name: tommy
Date: 2007-06-02 7:15:50 PM
Comment:
Hi again Haissiam
ihave change the code to what u states and now i'm gettint this error lne 66
Compiler Error Message: CS0103: The name 'Path' does not exist in the current context

Source Error:



Line 64: if (!System.IO.Directory.Exists(storePath))
Line 65: System.IO.Directory.CreateDirectory(storePath);
Line 66: hif.PostedFile.SaveAs(storePath + "/" + Path.GetFileName
Line 67: (hif.PostedFile.FileName));
Line 68:
Title: RE:Error   
Name: Haissam Abdul Malak
Date: 2007-06-02 1:32:12 PM
Comment:
Hey tommy, before you can use the Directory class you need to import the System.IO namespace by adding the below code
using System.IO; or you can use directy
if(!System.IO.Directory.Exists(storePath))
System.IO.Directory.CreateDirectory(storePath);

Thank you for your comment
Title: ERROR   
Name: TOMMY
Date: 2007-06-02 1:05:38 PM
Comment:
Hi Haissam cool article
I'm having a bit of trouble in line 61 whenever i tryed to run the code, any idea?


Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0103: The name 'Directory' does not exist in the current context

Source Error:



Line 59: {
Line 60: string storePath = Server.MapPath("~") + "/MultipleUpload";
Line 61: if (!Directory.Exists(storePath))
Line 62: Directory.CreateDirectory(storePath);
Line 63: hif.PostedFile.SaveAs(storePath + "/" + Path.GetFileName
Title: Re:What is this?   
Name: Haissam Abdul Malak
Date: 2007-05-31 8:42:47 AM
Comment:
You can for sure turn off your virus scanner for a while and download it. it doesnt contain anything GUARANTEED.

Regards,
Title: Re:Issues Issues   
Name: Haissam Abdul Malak
Date: 2007-05-31 1:49:04 AM
Comment:
You are right Kevin, but for this demonstration no other sessions are used that is why i deleted all the session and used the session count, but in this case you can use a predefined prefix in the session name which will allow you to search for, delete, and count it.

P.S: The comments were deleted because of expressing his idea in a disrespectful way.

Best Regards,
Title: Issues Issues   
Name: Kevin Jones
Date: 2007-05-30 10:24:48 PM
Comment:
Another issue: You are using Session.Count when the button upload is clicked. What if the user has something else in the session? It will screw up the counts.
Title: Re: Memory Issues   
Name: Kevin Jones
Date: 2007-05-30 7:44:26 PM
Comment:
OK, so someone has to upload 10 10MB files before it crashes. Secondly, you are calling Session.RemoveAll(). This empties the ENTIRE session. What if the developer is using session elsewhere in his app? You want to blank it out? Say 10 users upload 1 10MB file, you are still going to screw up the server.
Title: Comment   
Name: mike
Date: 2007-05-30 7:04:53 PM
Comment:
Why do want users to leave comment and yet you deleted it if you dont have the answer
Title: Wrong   
Name: Josh Stodola
Date: 2007-05-30 5:47:42 PM
Comment:
Lets see how long it will take you to delete this comment, Haissam.

The files are NOT uploaded at once like the article title suggests. They are uploaded when the Attach button is clicked. Therefore, this article is totally misleading. The title says one thing, the article does the exact opposite.

Not a very helpful article at all. In fact, this is a pretty bad approach to file uploading. Storing the files in the session is just plain stupid.
Title: Question!   
Name: Haissam Abdul Malak
Date: 2007-05-30 5:23:36 PM
Comment:
Just tell me how would you upload 100MB file size if the maxRequestLength was approximately 10MB!!!! Did you think of it!!
Thank you for your precious comment
Title: Memory Issues   
Name: vcsjones
Date: 2007-05-25 11:51:24 AM
Comment:
This has a huge problem. You are saving files into the Session?? What happens when I upload a 100 MB document? My Worker Process is going to increase it's memory usage by 100 MB, and that can have huge problems. All I need to do is upload 2 100 MB files and there is a good chance I will crash the worker process, or cause an Application Recycle.
Title: Delete File Flaw   
Name: Bill
Date: 2007-05-23 11:59:16 AM
Comment:
This is a nice idea, which works well until a file is removed from the listbox. When this happens the indices of the items above the deleted item change and this is not reflected in the session variables. As a result, there is a mismatch between session variables and listbox items, or so it appears to me.
Title: abadi   
Name: abadi
Date: 2007-05-20 7:04:37 AM
Comment:
Thanks very well
Title: Error   
Name: Oscar
Date: 2007-05-19 3:40:29 PM
Comment:
I have convert into VB and I'm getting an error on the following line

' Save the FileUpLoad control into a different session
Session("MyUpLoad" + i) = FileUpload


The error says that the 'FileUpload' is a type and cannot be used as an expression.


What could cause this?
Title: :error   
Name: Haissam Abdul Malak
Date: 2007-04-27 8:17:56 AM
Comment:
What type of error!!
Title: error   
Name: amanpreet
Date: 2007-04-27 7:53:11 AM
Comment:
its giving me error ....
Title: Re:vb code behind   
Name: Haissam Abdul Malak
Date: 2007-04-26 2:04:53 AM
Comment:
Check below post for free conversion tools

http://dotnetslackers.com/community/blogs/haissam/archive/2007/04/19/Conversion-Tools.aspx

HC
Title: Object Refrence Eroor   
Name: kapil
Date: 2007-04-26 1:17:49 AM
Comment:
{
Line 99: HtmlInputFile hif = (HtmlInputFile)Session["myupload" + i];
Line 100: if(hif.PostedFile.ContentLength <= 500000)
Line 101: {
Line 102: string storePath = Server.MapPath("~") + "/MultipleUpload";


That Error is Coming in your Code.

Reply on kapil.dev@comm-it.in
Title: vb code behind   
Name: zara
Date: 2007-04-26 1:00:41 AM
Comment:
can you provide me the vb code of the same.
Title: Flash alternative (with link!)   
Name: Paul
Date: 2007-04-24 10:52:02 AM
Comment:
Ooops... link not showing. Here you go...

http://www.codeproject.com/aspnet/FlashUpload.asp
Title: Flash alternative   
Name: Paul
Date: 2007-04-24 10:51:11 AM
Comment:
Hi,

Here is an alternative I use which makes uploading multiple files very easy. Yes it relies on Flash but it might be more suitable for somebody reading this article. Best of all you can highlight all your files in one go and upload all of them with visual feedback.

Best, Paul.
Title: Upload an entire directory?   
Name: Jerome
Date: 2007-04-23 5:46:59 PM
Comment:
Nice Article – It Causes Contemplation...
Can some java script coding be used to gather all file names and path information from a browsed directory into a single structure and the resulting structure then used to populate the list box and session variable mentioned in this article? This would be a nice feature for uploading a group images for a photo album. If you know of some java script command(s) to return a directories contents and root path then please provide an example.
Title: Re:Misleading Title   
Name: Haissam Abdul Malak
Date: 2007-04-23 3:25:08 PM
Comment:
It seems you didn't get the idea of this article my friend :) anyhow ALL the files are stored in the webserver when the Upload button is clicked and not the ATTACHED one!
So I think the title is not misleading anymore

Best Regards,
HC
Title: Misleading Title   
Name: Justin
Date: 2007-04-23 2:51:49 PM
Comment:
Great article, nice concept, but I feel the title is misleading.

By using the words "Upload" and "Once" together I assumed one http post of multiple files, but that's not what the code is doing.

With every postback of the "Attach" button you are uploading a file. You are not "Uploading Multiple Files at Once."
Title: Re:Upload Concern   
Name: Haissam Abdul Malak
Date: 2007-04-23 10:36:21 AM
Comment:
When clicking attach, we are just displaying the full file path selected by the user in the listbox control thus we arent handling the upload in this state. of course this won't affect the overall process, instead of uploading single files by clicking "attach" each time the user selects a file to be upload, we are grouping them and upload them like batch upload.

And for you Paul Bersand, if you know asp.net forums, you would know that most of these comments are from forums members(Check their name there), and like we mentioned, you can increase the files to be uploaded as much as you can for demonstration i used the 5 MB default size.
Thank you all for your comments

Best Regards,
HC
Title: I get an error   
Name: Adrian
Date: 2007-04-23 9:59:22 AM
Comment:
Hi, downloaded this today and get the following error when I click the Upload button...
Object reference not set to an instance of an object.
and the highlighted line is...
Line 100: if(hif.PostedFile.ContentLength <= 500000)

Is this a known bug or something weird on my computer ?
Title: Limited use   
Name: Paul Bersand
Date: 2007-04-23 9:36:47 AM
Comment:
Most people who want multiple upload functionalty want to load whole directories of 50+ files. If the number of upload controls is limited to a small amount, the gain from using this technique is minimal.

By the way, I think most of these comments were written by the same person judging by the language 'style'.
Title: Mr.   
Name: uzair zaman sheikh
Date: 2007-04-22 4:18:20 PM
Comment:
I really like that side because its a very good source to learn asp.net.
Title: Upload Concern   
Name: Jeremy S.
Date: 2007-04-22 2:10:08 PM
Comment:
This is a great utility/trick however if they are uploading several larger files are these not moved to the server with each "attach"? Wouldn't this slow down the overall process?
Title: Great tips   
Name: Liming Xu
Date: 2007-04-22 10:51:13 AM
Comment:
No wonder you are the "Top Gun" across all asp.net forums, very good tips and I'll have to implement this later into my own software.

Thanks man, really appreicate it.
Title: Re:Few Code bugs..   
Name: Haissam Abdul Malak
Date: 2007-04-16 2:37:03 AM
Comment:
Thank you Mandeep, for sure the first bug is a copy/paste bug not more. If you could tell me more about the second one it will be appreciated.

Best Regards,
HC
Title: Few Code bugs..   
Name: Mandeep Bhangu
Date: 2007-04-11 7:03:02 PM
Comment:
Cheers buddy for a nice trick....
In the upload click method, first line is missing ";" and also we need to reset the viewstate, alonf with resetting the cookies...

cheers
Title: RE:Good   
Name: Haissam Abdul Malak
Date: 2007-04-05 2:45:18 PM
Comment:
This is not implemented in this article. but i will try to create one for this purpose
Thank you for your comment

Best Regards,
HC
Title: Good   
Name: Prathi
Date: 2007-04-05 2:36:08 PM
Comment:
Really good work.. can v select one folder(contains multiple files) ? is it possible?
Title: Excellent   
Name: Kashif
Date: 2007-04-03 1:12:00 PM
Comment:
Thanks for sharing ur precious code and time
Its really very helpful.....and explained in a very good manner ..

Keep it up...
Title: Appreciated   
Name: Haissam Abdul Malak
Date: 2007-04-03 2:59:59 AM
Comment:
Thank you for sharing your comments!

Best Regards,
HC
Title: Nice Job Haissam   
Name: Irfan
Date: 2007-04-03 2:48:11 AM
Comment:
Very useful
Explained in good way .. very nice
Title: Uploading Multiple Files At Once   
Name: Honey
Date: 2007-03-29 7:56:26 AM
Comment:
Hi Haissam Abdul Malak,

You had given example elaborately and explained each and every step. You had done a great job. Every fresher in .net can easily understand this.Thanks a Lot

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-10-06 3:26:50 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search