Upload files from a client PC to a web server with ASP.NET

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);
            }
         }
      }