Create new account I forgot my password    

Uploading Multiple Files in ASP.NET 2.0
Rating: 71 user(s) have rated this article Average rating: 4.4
Posted by: Suprotim Agarwal, on 8/1/2007, in category "ASP.NET 2.0 & 3.5"
Views: this article has been read 80987 times
Abstract: In earlier versions of ASP.NET, you could use the HTML FileUpload control to upload files. However there were a couple of efforts required by the developer to do so. ASP.NET 2.0 introduces the FileUpload server control that makes the implementation smoother. In this article, we will first explore how to upload a file using the FileUpload control and then extend the functionality to upload multiple files.

Uploading Multiple Files in ASP.NET 2.0
In ASP.NET 2.0, the FileUpload control enables users to upload file from your web pages. The FileUpload control consists of a text box and a browse button. Clicking on the button allow users to select a file on the client and upload it to the server. Let us first start off by exploring how to upload a single file in asp.net. To do so, follow these steps:
Step 1: Drag and drop the FileUpload server control from the toolbox. The code behind looks as follows :
<asp:FileUpload id=”FileUpload1” runat=”server” />
Step 2: Drop a Button control and rename it to “Upload”
<asp:Button ID=”btnUpload” runat=”server” Text=”Upload” />
Step 3: Double click the Upload Button to add an event hander to the code behind.
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
 
}
VB.NET

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)

End Sub

 
Step 4: Add the following code to the event handler
C#
 
protected void btnUpload_Click(object sender, EventArgs e)
{
        try
        {
            if (FileUpload1.HasFile)
            {
                FileUpload1.SaveAs(Server.MapPath("MyFiles") +
                    "\\" + FileUpload1.FileName);
            }
        }
        catch (Exception ex)
        {
            // Handle your exception here
        }
 
}
VB.NET

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)

Try

 

If FileUpload1.HasFile Then

FileUpload1.SaveAs(Server.MapPath("MyFiles") & "\" & FileUpload1.FileName)

End If

Catch ex As Exception

' Handle your exception here

 

End Try

End Sub

The “HasFile” property of our FileUpload control helps us to determine if a file has actually been uploaded. We then use the "SaveAs" method to save the file to disk.
That is all you require to implement the FileUpload functionality in your web pages. In order to retrieve the metadata information of the file being uploaded, you can drop a Label control on to the form designer and use the PostedFile.FileName and PostedFile.ContentLength on the FileUpload control. This would give you the uploaded file’s name and size respectively. Eg:
Label1.Text = FileUpload1.PostedFile.FileName;
Label1.Text += FileUpload1.PostedFile.ContentLength;
Uploading Multiple Files
 
So far so good. Let’s extend the above sample to upload multiple files at a time. Follow these steps mentioned below to do so: 
Step 1: Drag and drop multiple (in our case four) FileUpload controls on to the designer.
Step 2: Drop a Button control and rename it to “Upload”
<asp:Button ID=”btnUpload” runat=”server” Text=”Upload” />
Step 3: Double click the Upload Button to add an event hander to the code behind.
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
 
}
 
VB.NET

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)

End Sub

Step 4: Import the System.IO namespace.
using System.IO; - C#

Imports System.IO - VB.NET

Step 5: Use the ‘HttpFileCollection’ class 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 code would look as follows:
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") + "\\" +
                      Path.GetFileName(hpf.FileName));                      
                }              
            }   
        }
        catch (Exception ex)
        {
            // Handle your exception here
        }
 
}
VB.NET

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)

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") & "\" & Path.GetFileName(hpf.FileName))

End If

Next i

Catch ex As Exception

' Handle your exception here

 

 

End Try

End Sub

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 of the file. To retrieve the filename and length of the file uploaded, we can use hpf.FileName and hpf.ContentLength respectively.
Well, that was simple to implement, wasn’t it! However there are a few points to be kept in mind.
Some important points to consider while uploading
 
1.    To save a file to the server, the account associated with ASP.NET must have sufficient permissions on the folder, where the files are being uploaded. This would usually be the ‘ASPNET’ account for Windows XP or a similar OS. In Windows Server 2003, the account used is ‘NETWORKSERVICE’. So you would be required to explicitly grant write permissions to these accounts on the folder.
 
2.    While uploading the files to a remote server, the default ASPNET user account used by ASP.NET does not have network permissions by default. The solution is to either give the account such permissions or use impersonation to have it run under a different account that has the permissions.
 
3.    By default, you can upload no more than 4096 KB (4 MB) of data. However there is a workaround for this limitation. 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. I would encourage you to experiment with the other attributes of the httpRuntime element.
<configuration>
      <system.web>
            <httpRuntime
               executionTimeout="200"
               maxRequestLength="8192"
               requestLengthDiskThreshold="256"
               useFullyQualifiedRedirectUrl="false"
               minFreeThreads="8"
               minLocalRequestFreeThreads="4"
               appRequestQueueLimit="5000"
               enableKernelOutputCache="true"
               enableVersionHeader="true"
               requireRootedSaveAsPath="true"
               enable="true"
               shutdownTimeout="90"
               delayNotificationTimeout="5"
               waitChangeNotification="0"
               maxWaitChangeNotification="0"
               enableHeaderChecking="true"
               sendCacheControlHeader="true"
               apartmentThreading="false"/>
      </system.web>
</configuration>
References
There are a number of good resources I referred to, for this article. A few of them are:
http://www.wrox.com/WileyCDA/Section/id-292160.html
http://msdn2.microsoft.com/en-US/library/aa479405.aspx
http://msdn2.microsoft.com/en-us/library/system.web.httpfilecollection.aspx
Conclusion
File uploading in ASP.NET has certainly improved from its earlier versions. However we as developers would like to perform way better than it does today. In this article, I made an attempt to use this control to upload multiple files to the server. I hope this article was useful and I thank you for viewing it.
 If you liked the article,  Subscribe to my RSS Feed.









Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by Jason on Monday, November 05, 2007 1:15 AM
nice code!!! i combined it with a javascript that posts multiple files..so instead of using multiple fileupload controls..i used a single control.. The HttpFileCollection was very helpful...Thanks
Comment posted by chetan thummar on Wednesday, January 02, 2008 1:07 AM
it nice article but if i want to upload multiple file at same time but file control added at run time how many as i want and then upload all posted file at same time.. like attech file in yahoo mail, gmail..   plz help me..
Comment posted by Suprotim Agarwal on Wednesday, January 02, 2008 7:26 AM
Hi chetan, take a look over here http://forums.asp.net/p/1071914/1569254.aspx#1569254
Comment posted by SUNNY on Saturday, March 29, 2008 8:41 AM
path is giving an error in vb.net code its showing path is not declare
Comment posted by Muhammad waqas on Friday, April 11, 2008 2:49 PM
if there should be downloading code of uploaded files
then i think it would be very nice
Comment posted by polesh on Wednesday, April 16, 2008 7:57 AM
Hi nice article.
But instead of placing four fileupload controls at a time. i want to add controls(fileupload) dynamically.
If u Can help me in this .. i'll b very thankful to u
Comment posted by yoonus on Saturday, May 24, 2008 6:17 AM
But instead of placing four fileupload controls at a time. i want to add controls(fileupload) dynamically.
If u Can help me in this .. i'll b very thankful to u
Comment posted by Suprotim Agarwal on Wednesday, May 28, 2008 9:17 AM
You have to use the Page_Init() to create them. What are the issues you face?
Comment posted by Ajay Kelkar on Friday, June 06, 2008 12:32 PM
How can we show progress bar for uploading file
any ideas....
Comment posted by Prem on Tuesday, June 10, 2008 1:24 AM
How to upload a file dynamically in a remote server through Asp.net 2.0.Can anyone help me ? It's Urgent!
Comment posted by Suprotim Agarwal on Tuesday, June 17, 2008 1:12 PM
Ajay: Take a look at this article
http://www.codeproject.com/KB/webforms/File_Upload_Progress_Bar.aspx

Prem: What do you mean by dynamically uploading a file?
Comment posted by Dheeraj Singh on Monday, September 08, 2008 8:02 AM
It is one of the best Article that read for this Particular
Topic.


thanks
Comment posted by Suprotim Agarwal on Monday, September 08, 2008 8:43 AM
Thanks Dheeraj :)
Comment posted by Anand Dave on Monday, October 27, 2008 12:49 PM
i want to add an array of the fileuploadcontrol how can i do it dynamically
Comment posted by Suprotim Agarwal on Wednesday, October 29, 2008 12:32 AM
Anand: Try this post
http://forums.asp.net/t/1156085.aspx
Comment posted by niti on Thursday, November 20, 2008 6:48 AM
i need to upload multiple files without adding multiple fileupload control..

waiting for reply...
plz help
Comment posted by phanideepthi on Saturday, March 21, 2009 5:54 AM
place one fileupload control and one button.when we click button certain no of fileupload controls should be added.can any one help me.
Comment posted by Rob on Saturday, May 09, 2009 7:08 PM
Not a single VB.NET example worked!!!
Comment posted by San on Tuesday, July 07, 2009 3:20 AM
Very nice article, thanx a lot.
Comment posted by echo on Sunday, July 12, 2009 8:15 PM
The name of this article is very misleading. Where does it talk about the “Multiple Files”?
Comment posted by deendayal soni on Tuesday, July 14, 2009 9:16 AM
this is very useful for me.thanking you
Comment posted by Suprotim Agarwal on Friday, July 17, 2009 2:46 AM
echo: Misleading? Are you sure you read the entire article by clicking on the 'Read More' link.

Comment posted by Garima Mishra on Monday, August 10, 2009 6:46 AM
I have a Multiview ,where in to one view i am adding the files and in to another view i am showing the uploaded files . This work i have performed using a session. But as user go back to last view the list of uploaded file get vanish . How can I retrive the list of uploaded Files.Please reply me favourable soon.
Comment posted by Suprotim Agarwal on Tuesday, August 11, 2009 1:12 AM
Garima: That happens since a postback occurs and the values are lost. You can either store the file details using properties or use viewstate or session to retain the values during postback.

Alternatively a non-postback mechanism will do. Check my article here where I have shown how to upload multiple files using jQUery- http://www.dotnetcurry.com/ShowArticle.aspx?ID=317
Comment posted by Johnny on Thursday, September 10, 2009 3:28 AM
Not working when used inside an update panel
Comment posted by Clifford D'Souza on Friday, November 20, 2009 8:13 AM
hey man the article is superb but i have a problem.
i want to configure the way the file list is displayed just as its shown in the link http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Examples
Example 7, 8 , 9 but in asp.net.
i tried a lot of things but without any success.
the code on the above link works fine as html but not if i use the FileUpload control in asp.net.


Help Needed.
Comment posted by Clifford D'Souza on Tuesday, February 09, 2010 2:31 AM
hey man the article is superb but i have a problem.
i want to configure the way the file list is displayed just as its shown in the link http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Examples
Example 7, 8 , 9 but in asp.net.
i tried a lot of things but without any success.
the code on the above link works fine as html but not if i use the FileUpload control in asp.net.
Comment posted by Rukmal on Wednesday, June 02, 2010 10:19 PM
Thank you very much , code helped alot
Comment posted by priya on Tuesday, June 08, 2010 6:37 AM
hey,very good article.......
thanks for such good helpfull article.......
Comment posted by ali on Wednesday, July 28, 2010 10:31 AM
tank you very much becuse  ur cod is very praty.

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

NEWSLETTER