Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Gauge for SharePoint
Search :       Advanced Search »
Home » ASP.NET 2.0/3.5 » How to: Upload a File in ASP.NET

How to: Upload a File in ASP.NET

This article shows how we can upload a text file.

Author Rank :
Page Views : 98839
Downloads : 1075
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
UploadAFile.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

In this article, I am going to show how we can upload a file. Here I am uploading  a .txt file and saving it in a predefined location. Let see this by a simple programme. Here I am using  an input tag highlighted with yellow colour for browsing the uploaded file.

The fileupload.aspx code is:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

 <title>File Upload Demostration</title>

</head>

 <body>

    <form id="Form1" method="post" runat="server">

     <table cellpadding="0" cellspacing="0" width="80%" align="center" border="4">

      <tr><td height="20px"></td></tr>

       <tr><td height="200px" align="center" valign="middle">

               <input id="MyFile"   type="file" size="81" name="File1" runat="server" />

                      <br /><br />

                             <asp:Button id="btnSubmit"   runat="server" Text="Submit" Width="139px" Height="30px" OnClick="btnSubmit_Click"></asp:Button>

                             <asp:Label id="lbl"   runat="server" Width="402px" Height="33px"></asp:Label>

                            

                             </td></tr></table>

                   </form>

</body>

</html>

The fileupload.aspx.cs is:

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    protected void btnSubmit_Click(object sender, EventArgs e)

    {

        

        if (MyFile.PostedFile.ContentLength == 0)

        {

            lbl.Text = "Cannot upload zero length file";

            return;

        }

        lbl.Text = MyFile.PostedFile.FileName;

       MyFile.PostedFile.SaveAs("c:\\UploadFile\\MyFile.PostedFile.FileName");

 

    }

}

When user run the application then the window will look like this:


Figure 1.

When user click on Browse button:



Figure 2.

After selecting the file the window will look like this:



Figure 3.

When user click on submit button.



Figure 4. The uploaded file will save in the directory specified as the destination path in .cs file.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Rahul Kumar Saxena
Rahul shows great interests in working with Microsoft technologies. He specializes in the implementation of DataBase & Graphics. His area of expertise includes: C#, ASP.NET,ADO.NET,Windows Forms & Web Services. He hails from background , Master's in Computer Application. With programming he loves photography, traveling and reading books.
(Talabpur*)
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.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Gauge for SharePoint
Become a Sponsor
 Comments
HI NICE by P Karthick On August 3, 2007
Hi Rahul, This is nice one keep upload some more applications Cheers, Karthick
Reply | Email | Modify 
Nice, but... by Michael On October 17, 2007
How could I maintain the original file's timestamps, etc.? Using File.Copy() method works locally, but I need that on the web server...
Reply | Email | Modify 
try this by Etienne On November 23, 2007

protected void btnSubmit_Click(object sender, EventArgs e)

{

if ((MyFile.PostedFile != null) && (MyFile.PostedFile.ContentLength > 0))

{

string fn = System.IO.Path.GetFileName(MyFile.PostedFile.FileName);

string SaveLocation = ("c:\\UploadFile" + "\\" + fn);

try

{

MyFile.PostedFile.SaveAs(SaveLocation);

lblMine.Text = "Thank you for submiting the following file:";

lblLabel.Text = MyFile.PostedFile.FileName;

}

catch (Exception ex)

{

lblLabel.Text = ("Error: " + ex.Message);

}

}

else

{

lblLabel.Text = "Please select a file first before clicking on the Submit Button!!!!!!";

}

Reply | Email | Modify 
Re: try this by satya anand On December 17, 2007

Hi its woking great..

But could u plz tell me ..

How can I upload specific files only (for example : .pdf files only)

How can I get the type of file ?

Reply | Email | Modify 
Hi by Etienne On November 23, 2007
Hi Great......it works but i cant upload a LARGE file.... Why is that? Etienne
Reply | Email | Modify 
Re: Hi by Matthew On February 4, 2008

I am looking for the same thing...  I need to upload images to a database that are 4Mb and more, but I cannot find anywhere online that addresses the issue I am having.

 

Reply | Email | Modify 
Re: Hi by Rahul Kumar On April 7, 2009
Hi Dear,
h r u.
If u want to upload more size file the in ur web.config file add this
<system.web>

<httpRuntime
executionTimeout="110"
maxRequestLength="30000"
requestLengthDiskThreshold="80"
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>

Reply | Email | Modify 
File Upload by satya anand On December 17, 2007
your program is working great..... could you plz tell me.. How to save the file as it is in the same format as in the previous....
Reply | Email | Modify 
nice by reer On December 30, 2008
another example here : http://www.mo8.co.il/WebControls.aspx
Reply | Email | Modify 
UpLoadFile Control by Ashish On January 3, 2009
how to assign a text in Text Box of UpLoadFile Control in ASP.Net
Reply | Email | Modify 
could i contact u plz????????? by zenny On April 6, 2009
hiii the code u hav posted is of real good help.... im a student in a college and trying to learn asp.net. there is nobody to help. could i get ur help or any contact plz plz plz plz plz plz plz...
Reply | Email | Modify 
Re: could i contact u plz????????? by Rahul Kumar On April 7, 2009
hi Zenny
u can contact me here..

4rahulsaxena@gmail.com
Reply | Email | Modify 
thanks by mohammed On April 6, 2009
thanks more
Reply | Email | Modify 
hi friends by zenny On April 8, 2009
i am able to upload the file.. now i hav to modify the file and save again in the oracle databse.. modify is not happening.... can any1 help?
Reply | Email | Modify 
hi!!!! nice source code by Ram Narain On April 14, 2009
nice source for file upload congrates for this
Reply | Email | Modify 
I GOT SOLUTION FROM HERE. I HOPE THIS IS VERY USEFUL FOR U,, by sarav On October 10, 2009
http://www.onlineatoz.net/onlineatoznet/forum/post/ToolBox-Standard-Control-FileUpload.aspx
Reply | Email | Modify 
hi by ruby On April 24, 2010
hi....could you help me to store files in database(sql server2005) using file upload tool.
Reply | Email | Modify 
Thank's a lot by Farid On June 18, 2010
Thank you for your useful code.
Works great.
Reply | Email | Modify 
how to upload .pdf files...? by Ruan On July 21, 2010

there some codes:
   string fileName =pdf.FileName;//?????
            if (fileName != null)//????
            {
                string postfix = System.IO.Path.GetExtension(fileName).ToString().ToLower();//?????       
                if (postfix == ".pdf" || postfix == ".rar" || postfix == ".doc" || postfix == ".jpg" || postfix == ".txt" || postfix == ".gif" || postfix == ".bmp" || postfix == ".xls")
                {
                    double size = pdf.FileContent.Length / 1024;
                    if (size <= 5120)
                    {
                        Regex reg = new Regex(@"\.\w*?$");
                        string path = "";
                        string reFileName = reg.Replace(fileName, "") + DateTime.Now.ToStr("yyyyMMdd") + DateTime.Now.Ticks + postfix;
                        string companyName = TSQL.ExecDr(this.getSQL("selectcompanybyId"), Session["CompanyID"].ToInt32())["com_name"].ToStr();// TSQL.ExecuteScalar(this.getSQL("selectcompanynamebyId"), Session["CompanyID"].ToInt32()).ToStr();
                        string foo = Server.MapPath("..//Js");
                        string folder = Server.MapPath("..//PdfFile") + "\\" + companyName;
                        if (Directory.Exists(folder))
                            path = folder + "\\" + reFileName.ToStr();
                        else
                        {
                            Directory.CreateDirectory(folder);
                            path = folder + "\\" + reFileName.ToStr();
                        }
                        pdf.SaveAs(path);
                        files = "../PdfFile/" + companyName + "/" + reFileName;
                        if (this.HiddenField1.Value == "")
                            TSQL.ExecuteNonQuery(this.getSQL("insertintockmt"), no.Text.ToStr(), name.Text.ToStr(), style.Text.ToStr(), date.Text.ToDateTime(), price.Text.ToDecimal(), power.Text.ToDecimal(), heigth.Text.ToDecimal(), width.Text.ToDecimal(), length.Text.ToDecimal(), weigth.Text.ToDecimal(), provider.Text.ToStr(), works.Text.ToStr(), Session["CompanyID"].ToInt32(), files);
                        else
                        {
                            if (pdfs.Value == "")
                                TSQL.ExecuteNonQuery(this.getSQL("updateckmt"), no.Text.ToStr(), name.Text.ToStr(), style.Text.ToStr(), date.Text.ToDateTime(), price.Text.ToDecimal(), power.Text.ToDecimal(), heigth.Text.ToDecimal(), width.Text.ToDecimal(), length.Text.ToDecimal(), weigth.Text.ToDecimal(), provider.Text.ToStr(), works.Text.ToStr(), files, this.HiddenField1.Value.ToInt32(), Session["CompanyID"].ToInt32());
                            else
                                TSQL.ExecuteNonQuery(this.getSQL("updateckmt"), no.Text.ToStr(), name.Text.ToStr(), style.Text.ToStr(), date.Text.ToDateTime(), price.Text.ToDecimal(), power.Text.ToDecimal(), heigth.Text.ToDecimal(), width.Text.ToDecimal(), length.Text.ToDecimal(), weigth.Text.ToDecimal(), provider.Text.ToStr(), works.Text.ToStr(), pdfs.Value.ToStr(), this.HiddenField1.Value.ToInt32(), Session["CompanyID"].ToInt32());
                            this.HiddenField1.Value = "";
                        }
                    }
                }
                else
                    this.ScriptManager1.alert("????pdf??,doc??,xls??,txt??,jpg??,gif??,bmp??,rar????");

 i use fileupload control ,  but  can't upload pdf files why...?
if you can help me , please send email for ruanjingbiao@163.com
thinks...

Reply | Email | Modify 
upload file by bhargav On August 17, 2010

Hi,
     This very nice article.

Reply | Email | Modify 
file retrieving by Deven On April 2, 2011
after saving the file .. we saved its address as a database field.... ok but how we will access that file at the front with the use of that address stored in database plz plz solve my query....
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.