How to Upload Files Using C# ASP.NET FileUpload Control

By FoxLearn 12/15/2024 2:27:07 PM   20
To upload a file using the FileUpload control in ASP.NET with C#, follow these steps.

The ASP.NET FileUpload control enables file upload functionality in web applications. It automatically sets the web form's encoding to "multipart/form-data," eliminating the need for manual configuration.

Implement Upload File using C# ASP.NET FileUpload Control

Open Visual Studio and create a new project, then select ASP.NET Web Application (.NET Framework). Choose the Empty project template, add folders and core references for Web Forms, and create the project.

Add a new ASPX page named FileUploadForm.aspx to implement the file upload functionality using the FileUpload control.

In your ASPX page, add the FileUpload control along with a button to trigger the file upload:

<asp:FileUpload id="FileUploadControl" runat="server" />
<asp:Button id="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
<asp:Label id="lblMessage" runat="server" ForeColor="Green" />
  • FileUploadControl: This is the control where users will select the file to upload.
  • btnUpload: The button that will trigger the upload.
  • lblMessage: A label to display success or error messages.

To save an uploaded file to a server folder, implement the button click event in the FileUploadForm.aspx.cs file. This server-side code will process the file upload and store the file on the server.

protected void btnUpload_Click(object sender, EventArgs e)
{
    if (!FileUploadControl.HasFile)
    {
        lblMessage.Text = "Please select a file to upload.";
        return;
    }
    try
    {
        // Specify the path to save the uploaded file string
        filePath = Server.MapPath("~/UploadedFiles/") + FileUploadControl.FileName;
        // Save the file to the server 
        FileUploadControl.SaveAs(filePath);
        // Display success message
        lblMessage.Text = "File uploaded successfully!";
    }
    catch (Exception ex)
    {
        // Handle any exceptions that occur during file upload
        lblMessage.Text = $"File upload failed: {ex.Message}";
    }
}

The FileUploadControl.HasFile property is used to check if the user has selected a file.

The SaveAs method saves the file to the specified path on the server. The Server.MapPath method converts a relative URL (like ~/UploadedFiles/) into an absolute server path.

After the file upload, a success or failure message is shown in the lblMessage label.

Ensure you have a folder called UploadedFiles in your project where the uploaded files will be saved. The folder must have appropriate write permissions for the server.

How to upload large files using ASP.NET FileUpload Control

In ASP.NET .NET Framework-based applications, the default maximum upload size is 4 MB (4096 KB). To increase or override this limit, you need to modify the web.config file by adding the appropriate settings to specify a higher upload file size limit.

<configuration>
  <system.web>
    <httpRuntime targetFramework="4.8" maxRequestLength="214748364" />
  </system.web>
</configuration>

How to restrict file yypes in ASP.NET FileUpload Control in C#

If you need to restrict file uploads to certain types, such as allowing only image files (e.g., *.jpg, *.png) for a user profile picture in your ASP.NET web application, you can set restrictions on the allowed file types. This ensures that users are only able to upload valid image files and prevents the upload of unsupported file formats like PDF for profile pictures.

Restricting file types in the ASP.NET FileUpload control is crucial for security, as it prevents users from uploading potentially harmful executable files or scripts that could exploit the application. To control allowed file types, you can use a Regular Expression Validator in your ASPX page to validate the file extension before allowing the upload.

For example, if you want to restrict uploads to only JPG and PNG files, you can add the appropriate Regular Expression Validator to the ASPX page. This ensures that only files with the specified extensions (JPG and PNG) are uploaded in your ASP.NET C# web application.

<asp:RegularExpressionValidator id="FileUpLoadValidator" runat="server" ErrorMessage="Only jpg & png are allowed for uploads" ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)$?)(\\(\w[\w].*))(.jpg|.JPG|.png|.PNG)$" ControlToValidate="FileUploadControl">
</asp:RegularExpressionValidator>

The above code adds validation to the ASP.NET FileUpload control, restricting uploads to only JPG and PNG file types. In the ControlToValidate parameter, you must specify the ID of the FileUpload control used in your web form.

Additionally, for the Regular Expression validation to function properly, ensure that the appropriate configuration is included in your web.config file.

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

The above configuration enables unobtrusive JavaScript for client-side validation in ASP.NET, ensuring that validator controls use the pre-4.5 behavior for validation.

After adding the configuration, if a user attempts to upload a file type other than JPG or PNG, a validation message will appear. The message, specified in the ErrorMessage parameter of the RegularExpressionValidator, will display: "Only jpg & png are allowed for uploads."

When you run the application, the user will be able to select a file and upload it by clicking the "Upload" button. If the upload is successful, the file will be saved in the UploadedFiles folder, and a success message will appear.