Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET & Web Forms » ASP.NET 2.0 FileUpload Control

ASP.NET 2.0 FileUpload Control

ASP.NET 2.0 FileUpLoad control is used to browse and upload a file from a web page. This tutorial shows how to use ASP.NET 2.0 FileUpload control.

Author Rank:
Technologies: .NET 1.0/1.1, ASP.NET 1.0,Visual C# .NET
Total downloads : 1554
Total page views :  292411
Rating :
 5/5
This article has been rated :  3 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ASPNetControls.zip
 
Become a Sponsor


Related EbooksTop Videos

Finally ASP.NET 2.0 has a FileUpLoad control, which allows developers to drop the control on a page and let it browse a file and upload it on the server.

To create a control, simply drop the FileUpload control from Toolbox to a Web page. The following code adds the FileUpLoad control:

<asp:FileUpLoad id="FileUpLoad1" runat="server" />

To support file upload, we need to add a Button control:

<asp:Button id="UploadBtn" Text="Upload File" OnClick="UploadBtn_Click" runat="server" Width="105px" />

Now on this button click event handler, we need to call SaveAs method of FileUpLoad control, which takes a full path where the file will be uploaded.

protected void UploadBtn_Click(object sender, EventArgs e)
{
if
(FileUpLoad1.HasFile)
{

FileUpLoad1.SaveAs(@"C:\temp\" + FileUpLoad1.FileName);
Label1.Text =
"File Uploaded: "
+ FileUpLoad1.FileName ;
}
else
{
Label1.Text =
"No File Uploaded."
;
}
}

The final page looks like Figure 1.

Figure 1. FileUpLoad control

Now if you run the sample, browse a file, and click on Upload File button, the output looks like Figure 2.

Figure 2. FileUpLoad control in action

Restricting File Types

You can restrict the FileUpload control to upload a file type. For example, I wanted to upload images (Jpgs and Gifs) only so I put a validator, which allows Gifs and Jpegs only.

<asp:RegularExpressionValidator
id="FileUpLoadValidator" runat="server"
ErrorMessage="Upload Jpegs and Gifs only."
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF)$"

ControlToValidate
="FileUpload1">
</asp:RegularExpressionValidator>

Figure 3. Validating images only.

I was trying to upload a file with over 10MB and was getting error and this is why?

The default size of files uploaded by the FileUpload control is 4MB. So if you try to upload the files larger than 4MB, it won't let you do so. To do so, you need to change the default file size in machine.config.comments file for maxRequestLength of httpRuntime tag.  This number is in KB.

<httpRuntime
executionTimeout = "110" [in Seconds][number
maxRequestLength = "4096" [number]
requestLengthDiskThreshold = "80" [number]
useFullyQualifiedRedirectUrl = "false" [true|false]
minFreeThreads = "8" [number]
minLocalRequestFreeThreads = "4" [number]
appRequestQueueLimit = "5000" [number]
enableKernelOutputCache = "true" [true|false]
enableVersionHeader = "true" [true|false]
apartmentThreading = "false" [true|false]
requireRootedSaveAsPath = "true" [true|false]
enable = "true" [true|false]
sendCacheControlHeader = "true" [true|false]
shutdownTimeout = "90" [in Seconds][number]
delayNotificationTimeout = "5" [in Seconds][number]
waitChangeNotification = "0" [number]
maxWaitChangeNotification = "0" [number]
enableHeaderChecking = "true" [true|false]
/>


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Mahesh Chand
Mahesh is a software developer with over 13 years of experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle. If you are looking for a Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
ASPNetControls.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor
 Comments
exporting and importing data from sql-server data base throuh excel sheet in ap.net web pages by satikanta On January 12, 2006

Hi !

Here just want a help for managing sqlserver database through excel sheet.As there is bulk of records to update ....

 

I am using asp.net 2.0

Please help me.

Reply | Email | Delete | Modify | 
Re: exporting and importing data from sql-server data base throuh excel sheet in ap.net web pages by Mahesh On January 12, 2006
Please post your question on C# Corner discussion forums by clicking on the Forum link at the top header of the site. This place is for the discussion about the article only.
Reply | Email | Delete | Modify | 
Doubt by ganapathy On May 15, 2006

 

Hi,

     I understand how to uplaod file but My doubt is .        I want browse & save one file in sql server-db .Then i want retrieve that file & display in screefn how i can implement. In the uplaoding   Uploadfile1.Postfile.filename --I gave means error is coming.

 Wat i have to .Can u clear me my doubt.

 

Regards,

G.Gayathri

 

 

Reply | Email | Delete | Modify | 
Where is machine.config.comments ? by Vicky On July 17, 2006

Your article was very helpful to me. Since im new to .net, can you plz tell me where is that machine.config.comments? That is different than web.config right?

Thanks.

Vicky

Reply | Email | Delete | Modify | 
Re: Where is machine.config.comments ? by Mahesh On May 19, 2007
Yes it is different than web.config. Web.config is for each application and in the application project but machine.config is one for the machine. You may want to search this on your machine.
Reply | Email | Delete | Modify | 
Regarding Folder browse only by Dheeraj On March 9, 2007
I want to use the file upload control only for browsing the folder and settinf the destination folder only not a file upload ...is it possible
Reply | Email | Delete | Modify | 
Folder Browse by Dheeraj On March 9, 2007
Can i restrict the file upload control, just to browse folder level not file..or any other way to do this in asp.net
Reply | Email | Delete | Modify | 
Theme for FileUpload control by sachin On May 15, 2007
Hi Mahesh, How to apply theme to Browse button of fileUpload control?
Reply | Email | Delete | Modify | 
Re: Theme for FileUpload control by Mahesh On April 2, 2009
Search this site. You will find custom file upload control and you can modify these controls the way you want.
Reply | Email | Delete | Modify | 
File Upload control by K V S On July 27, 2007

I am facing some problems in uploading files on to the webserver..its all working fine on the development machine/server..i am actually saving the file extension onto the database and then upload the file by renaming with the primary key..it gives Security Exception...but i have given write permission to the folders still it does'nt work can some one help me out..my code is something like this



Dim message As String = ""

If fuImage.HasFile Then

message = ImageHelper.ValidateImageFile(fuImage)

If message <> "" Then

Throw New Exception(message & "(Image)")

End If

End If

Dim fi As New IO.FileInfo(fuImage.PostedFile.FileName) objServices.ServiceImage = fuImage.FileName

Dim PhotoId As Integer = objServicesBO.InsertMrservices(objServices) ImageHelper.UploadTheFile(fuImage, "Photos", PhotoId)

ViewState("id") = PhotoId

pls do mail me if you have solution to srenvas_2511@yahoo.com



thanks Srenvas

Reply | Email | Delete | Modify | 
Need suggestion by Asifkhan On July 30, 2007
Hi, i m using File upload control of 2.0 framework.I m seleting the file using browse button of file upload control,But due to postback event of any other control on my page the content of file upload control textbox (where the path of selected file is displayed ) gets cleared!!!!!!!!!! I m not getting how to solve this??????????
Reply | Email | Delete | Modify | 
Re: Need suggestion by Mahesh On September 27, 2007
It looks like you have view state of your controls turned off. You need to make sure view state is on.
Reply | Email | Delete | Modify | 
Re: Re: Need suggestion by Juan On May 13, 2009
How i can to do this, becouse in Page_Load i can't asign the file seted before to FileUpload comtrol.
Reply | Email | Delete | Modify | 
Re: Re: Need suggestion by Juan On May 13, 2009
How i can to do this, becouse in Page_Load i can't asign the file seted before to FileUpload comtrol.
Reply | Email | Delete | Modify | 
Re: Re: Re: Need suggestion by Mahesh On May 13, 2009
Try to put your code on OnPrerender event. This event is fired after page load.
Reply | Email | Delete | Modify | 
how to pass huge data into database. by mansoor On September 25, 2007
iam having a webform containing 7 fileupload controls, the problem is that i am unable to upload more than 4mb datafile, in the database., i mean to say that ,suppose in 1 file upload control takes 2mb file and the other 2mb file,if i want to insert another file in third upload control, then the page is showing error. how ican pass huge data into database
Reply | Email | Delete | Modify | 
File upload Control by Jayanth On October 3, 2007
Hi Mahesh, i am struck in one problem & looking 4 solution. i have got one file upload control in asp.net 2.0. here the user will select a file fom D:\test.txt & on click of upload i should change the file name as test.txt.new & should upload the new file to the server. how i should do this? please help me.
Reply | Email | Delete | Modify | 
i need your suggestion by kirti On October 11, 2007
if we put Response.Write(Request.param) on our asp.net page(.cs) then we will see all control on that page but file uplad control not seen so what i can do to display it please help me
Reply | Email | Delete | Modify | 
This doesn't works for a remote sewrver uploading. by Sandeep On December 19, 2007
This doesn't works for a remote sewrver uploading.. I have tried a couple of times with different approaches but didn't suceeded. Any help on that?
Reply | Email | Delete | Modify | 
Machine Change Effect by Kasam On January 10, 2008
Will changing in machine.config, reflects any adverse effect in Project or machine.
Reply | Email | Delete | Modify | 
Re: Machine Change Effect by Mahesh On April 2, 2009
Pls post your question on forums that are not related to this article.

Changing machine.config will change settings for all projects on your machine.
Reply | Email | Delete | Modify | 
Hi by t On January 24, 2008
could you advise that,by using FileUpload control,how to save the obtained document content (pic or text) to the field of SQL database?
Reply | Email | Delete | Modify | 
Re: Hi by Mahesh On April 2, 2009
Search this site on how to read write an image to a database. There are several samples on this topic.
Reply | Email | Delete | Modify | 
image upload by pavan On March 3, 2008
i am developing a web application in that i am retrieving column values toa grid view control from database table . what i require now is when user uploading the image that imge should be store in the images folder of the project directory. and iwant to get that image file path of images folder and place that path in databas table imge_url field to retrieve image to a grid.
Reply | Email | Delete | Modify | 
File Upload in Windows Application. by Mazharkhan On March 7, 2008
Hi I am Mazharkhan, I have a Problem that i dont know how to Upload file in ASP.Net 2003 Using Visual Basic. Plz Give me some Advice About that... Thanks.
Reply | Email | Delete | Modify | 
Re: File Upload in Windows Application. by Mahesh On April 2, 2009
This same code should work. You need to just change code from C# to VB.NET. Here is a free utility to do so:
http://www.kamalpatel.net/ConvertCSharp2VB.aspx
Reply | Email | Delete | Modify | 
File Type Option List by pei On March 20, 2008
How can I restrict file type option list in the pop-up box to anything other than the default, which is gif, jpg, htm and html? Thanks!
Reply | Email | Delete | Modify | 
Re: File Type Option List by Mahesh On April 2, 2009
You need to change the expression below with the file types you want to browse.

(.jpg|.JPG|.gif|.GIF)
Reply | Email | Delete | Modify | 
Format file upload 's textbox by Roger On August 18, 2008
Is it possible to format the fileupload control's textbox? I want to extend the width of the textbox but i have no luck to get any properties to make it longer. any suggestion?
Reply | Email | Delete | Modify | 
Format file upload 's textbox by Roger On August 18, 2008
Is it possible to format the fileupload control's textbox? I want to extend the width of the textbox but i have no luck to get any properties to make it longer. any suggestion?
Reply | Email | Delete | Modify | 
Re: Format file upload 's textbox by Mahesh On April 2, 2009
Search this site for file upload control. There are many custom controls that you can modify the way you want.
Reply | Email | Delete | Modify | 
Format file upload 's textbox by Roger On August 18, 2008
Is it possible to format the fileupload control's textbox? I want to extend the width of the textbox but i have no luck to get any properties to make it longer. any suggestion?
Reply | Email | Delete | Modify | 
dont want entire path when clicking on fileupload control. by harshil On January 18, 2009
i used fileupload control in my project.but i dont wannt to show the entire path when i click on brrowse button.can anyone help me out?
Reply | Email | Delete | Modify | 
how to open uploaded files for editing by shraddha On January 21, 2009
Hi Mahesh and everyone there, I have a problem I want to get uploaded the file and upon revisit the user can open edit his/her file and save the changes back to the database/folder. Can anyone help me out in this? thanks Guria
Reply | Email | Delete | Modify | 
Re: how to open uploaded files for editing by Mahesh On April 2, 2009
When you say View and Edit the file, what file type are we talking about? It may not be possible unless you have that file viewer/editor integrated in your web application.

One way to do is, you download the file, edit it and then delete the existing file on the server and upload the new file.

Sorry! But there is no easy way to do it.
Reply | Email | Delete | Modify | 
Image Resolution by Hardik On January 29, 2009
how can we check the resolution of the image? For example 240*240?
Reply | Email | Delete | Modify | 
Re: Image Resolution by Mahesh On April 2, 2009
You can use Size or Width and Height properties of Image class to find out the size of an image in pixels. Search this site on how to view images using Image class or Bitmap class and load your image file and use the above properties.
Reply | Email | Delete | Modify | 
problem when using Gaia Ajax by chand On May 30, 2009
there will be no file upload, if u tried to use Ajax ennabled button<gaia:Button>  instead of <asp:Button>. so if any one is using ajax ennabled tools be carefull.this fileuploades needs a postback!
Reply | Email | Delete | Modify | 
binding data to fileupload by shanwaj On June 12, 2009
Hi Mahesh Chand
   I am trying to bind values from database table to fileupload control.how can I do that.Please help me how can i bind values to fileupload control. 
Reply | Email | Delete | Modify | 
binding data to fileupload by shanwaj On June 12, 2009
Hi Mahesh
   I want to bind data from database table to file upload control .please help me how can i bind data to file upload control
Reply | Email | Delete | Modify | 
FUPhoto by hamid On July 1, 2009

FUPhoto

Reply | Email | Delete | Modify | 
FileUpload Control by manna On September 6, 2009

Hi

I want to customise th FileUpload control layout and chenge the word "Browse..." but I can`t, would you help me please ?

Reply | Email | Delete | Modify | 
regular expression term "\w+" doesn't include the period by james.a.frisby On November 16, 2009
Great article, thanks.  On my application, I found that the regular expression would not allow unc file names where the server name contained a "." (period), as in "\\server.name\path\file.ext"

I changed the regular expression from
 "^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF)$"
to
"^(([a-zA-Z]:)|(\\{2}[\w\.]+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF)$"

Jim Frisby
Alaska

This solved my problem.
Reply | Email | Delete | Modify | 
Re: regular expression term "\w+" doesn't include the period by Mahesh On November 16, 2009
Thanks James for sharing your tip with us.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved