Search Amazon:

Upload files to the web server with ASP.NET

ASP.NET makes it easy for web applications to upload files from your local PC to the web server via the System.Web.UI.HtmlControls namespace. This namespace provides the HtmlInputFile server control. The HtmlInputFile control enables programming of the HTML <input type=file> element on your web page.

Here is an HTML excerpt from a web page. Note that all tags have the runat="server" attribute to allow you to manipulate the HtmlInputFile control in the web pages's code-behind. As mentioned, the input type is file and the form's encryption type is multipart/form-data.

    <form runat="server" enctype="multipart/form-data">
        <input runat="server" id=fileImport type=file>
        <asp:Button runat="server" id=btnUpload text="Upload"></asp:Button>
    </form>

In the code behind (C# in this case), include the System.Web.UI.HtmlControls namespace, declare a variable of type HtmlInputFile, and add a handler for the Upload button's click event:

    using System.Web.UI.HtmlControls;
    ...
    protected System.Web.UI.HtmlControls.HtmlInputFile fileUpload;    
    ...    
    this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
 

Add code in the web page's Upload button click event to transfer the file. In this example a guid is used to give the file is unique name and the file is stored in the UpLoads folder on the server.

      private void btnUpLoad_Click(object sender, System.EventArgs e)
      {
         if (fileImport.PostedFile != null)
         {
            try
            {
               Guid   guid = Guid.NewGuid();
               string toFile = Server.MapPath("UpLoads\\") + guid.ToString() + ".txt";

               fileImport.PostedFile.SaveAs(toFile);
            }
            catch (Exception ex)
            {
               System.Console.WriteLine("{0}", ex.Message);
            }
         }
      }
 
Sign In
  User Id 
  Password 


Submit Your Own Code and Articles




About TheScarms
About TheScarms

Ask me your programming questions

I read every email and answer all I can.

User Feedback: Be the first to add a comment! Items to Show:     

     
You must log in to post feedback.
Comment:    
 

If you use this code, please mention "www.TheScarms.com"

Email this page


TheScarms AppSentinel lets you securely copy protect and create evaluation versions of your software

TheScarms(tm) AppSentinel lets you quickly and easily create evaluation versions of your software and stop unauthorized copying and unregistered use of your programs!

Get your free
trial copy today!


      The World's Number 1 Web Host

© Copyright 2008 TheScarms