FileUpload in ASP.NET

The two controls used to upload files to a web server are:

  • HtmlInputFile - an HTML server control
  • File Upload - an ASP.NET server control

FileUpload is more popular because it automatically sets the encoding of the form, but HtmlInputFile does not.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

What Is FileUpload in ASP.NET?

ASP.NET’s FileUpload is an input controller used to upload files to a server. It appears on the screen with a browse button and opens up a dialogue box to choose a file or multiple files to upload from the local storage to the server.

This is a server-side control provided by ASP.NET. Implementing this feature is quite easy. ASP.NET also provides its own tag for this. An example could be:

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

Html code produced for the browser looks like:

<input name="Sample1" id="FileUpload1" type="file">  

FileUpload: Properties and Their Uses:

AccessKey

Set a keyboard shortcut for the control.

TabIndex

Set the tab order of the control.

BackColor

Set the background color.

BorderColor

Set the color of the border.

BorderWidth

Set the width of the border of the control.

Font

Set the font of the text within the control.

ForeColor

Set the color of the text.

Text

Set the text, shown for the control.

ToolTip

Displays the text when hovering over the control.

Visible

Set the visibility of control.

Height

Set the size.

Width

Set the width.

AllowMultiple

Allows multiple uploads at a time.

Example

The following code example explains the properties’ uses, using comments on appropriate places. This is the C# code for a “save button” on a web form. You can see several properties such as ContentLength, ContentType, and FileName, similarly shown in the example code given below.

Code :

protected void btnsave_Click(object sender, EventArgs e)

{

   StringBuilder sb = new StringBuilder();

   if (FileUpload1.HasFile)

   {

      try

      {

         sb.AppendFormat(" Uploading file: {0}", FileUpload1.FileName);         

         //saving the file

         FileUpload1.SaveAs("<c:\\SaveDirectory>" + FileUpload1.FileName);    

         //Showing the file information

         sb.AppendFormat("<br/> Save As: {0}",  FileUpload1.PostedFile.FileName);

         sb.AppendFormat("<br/> File type: {0}",    FileUpload1.PostedFile.ContentType);

         sb.AppendFormat("<br/> File length: {0}",  FileUpload1.PostedFile.ContentLength);

         sb.AppendFormat("<br/> File name: {0}",  FileUpload1.PostedFile.FileName);        

      }catch (Exception ex)

      {

         sb.Append("<br/> Error <br/>");

         sb.AppendFormat("Unable to save file <br/> {0}", ex.Message);

      }

   }

   else

   {

      lblmessage.Text = sb.ToString();

   }

}

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

How Does a FileUpload Control in ASP.Net Look Like?

A FileUpload control on a form looks like this:

FileUpload_in_ASP.NET_1

Where Is FileUpload Used?

FileUpload control generally appears on an HTML form, a website, or more commonly, on a Google Form. It is used in places where we need to upload and save files to a server for future use. 

What Is FileUpload in ASP.NET? How to Use Fileupload Control in a Web Form?

As shown in the example above, you just need to include one line to use FileUpload control in ASP.  But, the entire code for a simple web form that has nothing except a “Browse” button in ASP.NET looks like this:

// FileUploadSample.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"   

Inherits="WebFormsControlls.WebControls" %>  

<!DOCTYPE html>  

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

<head runat="server">  

    <title></title>  

</head>  

<body>  

    <form id="form1" runat="server">  

        <div>  

            <p>Browse to Upload File</p>  

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

        </div>  

        <p>  

            <asp:Button ID="Button1" runat="server" Text="Upload File" OnClick="Button1_Click" />  

        </p>  

    </form>  

    <p>  

        <asp:Label runat="server" ID="FileUploadStatus"></asp:Label>  

    </p>  

</body>  

</html>

Output in the browser:

FileUpload_in_ASP.NET_2.

The above code won’t work alone because the logic behind the save button or “Upload File” is missing. To add logic to the button, you must add a C# code. An example would look like this:

// FileUploadSample.aspx.cs

using System;  

using System.Collections.Generic;  

using System.Linq;  

using System.Web;  

using System.Web.UI;  

using System.Web.UI.WebControls;  

namespace WebFormsControlls  

{  

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

    {  

        protected System.Web.UI.HtmlControls.HtmlInputFile File1;  

        protected System.Web.UI.HtmlControls.HtmlInputButton Submit1;  

        protected void Page_Load(object sender, EventArgs e)  

        {  

        }  

        protected void Button1_Click(object sender, EventArgs e)  

        {  

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

            {  

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

                string SaveLocation = Server.MapPath("upload") + "\\" + fn;  

                try  

                {  

                    FileUpload1.PostedFile.SaveAs(SaveLocation);  

                    FileUploadStatus.Text = "The file has been uploaded.";  

                }  

                catch (Exception ex)  

                {  

                    FileUploadStatus.Text = "Error: " + ex.Message;  

                }  

            }  

            else  

            {  

                FileUploadStatus.Text = "Please select a file to upload.";  

            }  

        }  

    }  

}  

This code adds logic to the “Upload File” button that appears on the screen, i.e., it uploads the selected file to the server so when developers open their databases, it is visible to them, and the file can thus be used for future purposes.

The entire process goes like this:

#Opening Screen

FileUpload_in_ASP.NET_3

#After selecting a file “c# programs.txt.”

FileUpload_in_ASP.NET_4

#After successfully uploading the file.

FileUpload_in_ASP.NET_5.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

How to Restrict File Types in ASP.NET?

To restrict the sort of files uploaded to the server, you can use a validator/regex. Suppose you want to upload only jpg and gifs only. In that case, the following code would do the job.

Code:

<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> 

If you try to upload files that are not jpg or gifs, it shows an error like this:

FileUpload_in_ASP.NET_6.

Conclusion

FileUpload control is a very efficient and robust control for uploading files to a server, but this is just the back end of the code. 

If you want to learn the entire Full-Stack Web Development, our extensive Post Graduate Program in Full Stack Web Development, in collaboration with Caltech CTME, covers all the essential topics required for developing and honing front-end and back-end Java skills, and industry-related technologies, such as Agile and DevOps. Enrol now and scale up your development career today!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.