ASP.NET Web Forms FileUpload Control: Handling File Uploads

Learn how to use the FileUpload control in ASP.NET Web Forms to enable file uploads in your web applications. This tutorial provides code examples demonstrating how to handle uploaded files on the server, including file saving, validation, and error handling.



ASP.NET Web Forms FileUpload Control

What is the FileUpload Control?

The FileUpload control in ASP.NET Web Forms allows users to upload files from their computer to your web server. It creates a "Browse" button on your web page that opens a file selection dialog.

Creating a FileUpload Control

You can add a FileUpload control to your web form by dragging it from the Visual Studio toolbox. You can also add it directly to your ASPX code:

Code

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

FileUpload Control Properties

The FileUpload control has several properties to customize its behavior:

  • AllowMultiple: Allows users to select multiple files for upload (set to `true` or `false`).
  • Other properties control appearance (e.g., BackColor, ForeColor, Font, ToolTip).

Example: File Upload and Handling

This example demonstrates how to implement a file upload control and handle the uploaded file on the server.

WebControls.aspx (ASPX):

Code

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

Browse to Upload File: <asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" /><br />
<asp:Label ID="FileUploadStatus" runat="server" />

WebControls.aspx.cs (Code-Behind):

Code

using System;
using System.IO;
using System.Web.UI.WebControls;

namespace WebFormsControlls
{
    public partial class WebControls : System.Web.UI.Page
    {
        protected void Button1_Click(object sender, EventArgs e)
        {
            if ((FileUpload1.PostedFile != null) && (FileUpload1.PostedFile.ContentLength > 0))
            {
                string fn = Path.GetFileName(FileUpload1.PostedFile.FileName);
                string saveLocation = Server.MapPath("upload") + "\\" + fn; // Make sure the "upload" folder exists!
                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.";
            }
        }
    }
}

Remember to create an "upload" folder in your project's directory to store the uploaded files.