Handling Multiple File Uploads in ASP.NET: A Practical Guide

Learn how to implement multiple file uploads in your ASP.NET applications. This tutorial provides a step-by-step guide, covering the configuration of the FileUpload control and the code-behind logic for handling multiple files. Improve your ASP.NET file upload capabilities with this practical example.



Handling Multiple File Uploads in ASP.NET

Introduction to Multiple File Uploads

The ASP.NET FileUpload control allows you to upload files to your web server. To enable multiple file uploads, you set the AllowMultiple property of the FileUpload control to true. This tutorial demonstrates how to implement multiple file uploads in an ASP.NET application.

Creating a Multiple File Upload Form

Create an ASP.NET Web Form. Add a FileUpload control and a button. Set the AllowMultiple property of the FileUpload control to true.

ASPX Code (UploadMultipleFilesExample.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UploadMultipleFilesExample.aspx.cs" Inherits="UploadMultipleExample.UploadMultipleFilesExample" %>
<form id="form1" runat="server">
    <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
    <br />
    <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
    <br />
    <asp:Label ID="FileUploadStatus" runat="server"></asp:Label>
</form>

Handling Multiple File Uploads (Code-Behind)

The code-behind file handles the file uploads. When the user clicks the upload button, the code iterates through the uploaded files, saves them to the server, and displays a confirmation message.

C# CodeBehind (UploadMultipleFilesExample.aspx.cs)

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace UploadMultipleExample
{
public partial class UploadMultipleFilesExample : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        if ((FileUpload1.PostedFile != null) && (FileUpload1.PostedFile.ContentLength > 0))
        {
            int count = 0;
            foreach (HttpPostedFile uploadedFile in FileUpload1.PostedFiles)
            {
                string fileName = System.IO.Path.GetFileName(uploadedFile.FileName);
                string savePath = Server.MapPath("upload") + "\\" + fileName;
                try
                {
                    uploadedFile.SaveAs(savePath);
                    count++;
                }
                catch (Exception ex)
                {
                    FileUploadStatus.Text = "Error: " + ex.Message;
                }
            }
            FileUploadStatus.Text = count + " files uploaded.";
        }
        else
        {
            FileUploadStatus.Text = "Please select files to upload.";
        }
    }
}
}
Output

(Screenshots illustrating the file upload process, showing the initial empty upload folder, the files being uploaded, and the confirmation message after upload, would be included here.)