Using File Upload control in ASP .NET
.NET

Using File Upload control in ASP .NET

Mishel Shaji
Mishel Shaji

With the help of file upload control ( introduced in .NET v2.0 ), accepting files from users is no longer a difficult task.

The File Upload control makes it possible to upload files to the server in a few lines of code.

How to use File Upload control

You can simple drag a file upload control from the Toolbox or you can write the following markup to create one.

<asp:FileUpload ID="FileUpload1" runat="server" />

To learn the working of the control, I am adding two labels and a button to my form. Here’s my markup.

<body>
     <form id="form1" runat="server">
         <asp:FileUpload ID="FileUpload1" runat="server" />
         <asp:Button ID="btnupload" runat="server" Text="Upload" OnClick="btnupload_Click"/>
         <br />
         <asp:Label ID="txtmessage" runat="server" Text="Message: "></asp:Label>
         <br />
         <asp:Label ID="txtdetails" runat="server" Text="File Details: "></asp:Label>
     </form>
 </body>

As you can see, I have created two labels, one for showing the file upload status and the other one for showing the file details such as file size and file type.

Now we are going to write the C# code to upload file to the server in the button click event.

First add reference to System.IO namespace.

using System.IO;

Then, modify the code in your button click event handler as shown below.

protected void btnupload_Click(object sender, EventArgs e)
{
     if (FileUpload1.HasFile)
     {    
         //Displaying some metadata 
         txtdetails.Text += "File type: " + FileUpload1.PostedFile.ContentType;
         txtdetails.Text += "File Size (bytes): " + FileUpload1.PostedFile.ContentLength;

         //Create directory if not exixts
         if (!Directory.Exists(Server.MapPath("~/Uploads")))
         {
             Directory.CreateDirectory(Server.MapPath("~/Uploads"));
         }

         string filename = Path.GetFileName(FileUpload1.FileName);
         string path = Server.MapPath("~/Uploads/") + filename;

         //Saving file
         FileUpload1.SaveAs(path);
         txtmessage.Text= "File saved at " + path;
     }
}

What’s next???

Run your project, click on the File upload button to select a file and click the Upload button. You will see an output similar to the one shown below.

Output of file upload using the file upload control in ASP .NET