File Upload and Download in ASP.NET

File Upload is an input controller that is used to upload files to the server. It will create a browse button on the form that pops up a window to select the local machine’s file.

To implement FileUpload, we can drag it from the toolbox in visual studio.

This is a server-side control, and ASP.NET provides its tag to create it. The example is given below.

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

The server renders it as the HTML control and produces the following code to the browser.

<input name="FileUpload" id="FileUpload" type="file">

FileUpload Property Window:

ASP FileUpload 1

Example:

Here, we are going to implement file upload control in a web form.

// WebControlForm.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControlForm.aspx.cs"   
Inherits="WebFormsControlls.WebControls" %>  
<!DOCTYPE html>  
<html xmlns="https://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title></title>  
</head>  
<body>  
    <form id="upload" runat="server">  
        <div>  
            <p>Browse to Upload File</p>  
            <asp:FileUpload ID="FileUpload" runat="server" />  
        </div>  
        <p>  
            <asp:Button ID="upload" runat="server" Text="Upload File" OnClick="Button_Click" />  
        </p>  
    </form>  
    <p>  
        <asp:Label runat="server" ID="UploadStatus"></asp:Label>  
    </p>  
</body>  
</html> 

Code

// WebControlForm.aspx.cs
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web; 
using System.Web.UI.WebControls;  
namespace WebFormsControlls  
{  
    public partial class WebControls : System.Web.UI.Page  
    {  
        protected System.Web.UI.HtmlControls.HtmlInputFile File;  
        protected System.Web.UI.HtmlControls.HtmlInputButton Submit;  
        protected void PageLoad(object sender, EventArgs e)  
        {  
        }  
        protected void Button_Click(object sender, EventArgs e)  
        {  
            if ((FileUpload.PostedFile != null) && (FileUpload.PostedFile.ContentLength > 0))  
            {  
                string fn = System.IO.Path.GetFileName(FileUpload.PostedFile.FileName);  
                string SaveLocation = Server.MapPath("upload") + "\\" + fn;  
                try  
                {  
                    FileUpload.PostedFile.SaveAs(SaveLocation);  
                    UploadStatus.Text = "The file has been uploaded.";  
                }  
                catch (Exception ex)  
                {  
                    UploadStatus.Text = "Error: " + ex.Message;  
                }  
            }  
            else  
            {  
                UploadStatus.Text = "Please select a file to upload.";  
            }  
        }  
    }  
} 

We will then create a directory into the project to store uploaded files as we did in the below screenshot.

ASP FileUpload 2

Output:

Run the code. It produces the following output.

ASP FileUpload 3

We are now uploading a file c# programs.txt.

ASP FileUpload 4

It now displays a successful file uploaded message after uploading, as shown in the following screenshot.

ASP FileUpload 5

This file is stored in the upload folder. Look inside the folder, and it shows the uploaded file is present.

ASP FileUpload 6

ASP.NET Upload Multiple Files:

ASP.NET FileUpload control provides AllowMultiple property for uploading multiple files to the server that takes either true or false value.

The <asp:FileUpload> tag is used for creating a browse button to upload a file. Let’s create an example to upload multiple files.

Example:

This example contains the following files.

// UploadMultipleFilesExample.aspx
<%@ Page Language="C#" AutoEventWireup="true"   
CodeBehind="UploadMultipleFilesExample.aspx.cs" Inherits="UploadMultipleExample.UploadMultipleFilesExample" %>  
<!DOCTYPE html>    
    <html xmlns="https://www.w3.org/1999/xhtml">    
    <head runat="server">    
        <title></title>    
    </head>    
    <body>    
        <form id="multiple" runat="server">    
            <div>    
                <h3>Upload Multiple Files</h3>    
                <asp:FileUpload ID="FileUpload" runat="server" AllowMultiple="true" />    
            </div>    
            <p>    
                <asp:Button ID="upload" runat="server" Text="Upload File" OnClick="Button_Click" />    
            </p>    
        </form>    
        <p>    
            <asp:Label runat="server" ID="UploadStatus"></asp:Label>    
        </p>    
    </body>    
    </html>    
// UploadMultipleFilesExample.aspx.cs
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
namespace UploadMultipleExample  
{  
    public partial class UploadMultipleFilesExample : System.Web.UI.Page  
    {  
        protected void PageLoad(object sender, EventArgs e)  
        {  
        }  
        protected void Button_Click(object sender, EventArgs e)  
        {  
            if ((FileUpload.PostedFile != null) && (FileUpload.PostedFile.ContentLength > 0))  
            {  
                var count = 0;  
                foreach (HttpPostedFile uploadedFile in FileUpload.PostedFiles)  
                {  
                    string fn = System.IO.Path.GetFileName(uploadedFile.FileName);  
                    string SaveLocation = Server.MapPath("upload") + "\\" + fn;  
                    try  
                    {  
                        uploadedFile.SaveAs(SaveLocation);  
                        count++;  
                    }  
                    catch (Exception ex)  
                    {  
                       UploadStatus.Text = "Error: " + ex.Message;  
                    }  
                }  
                if (count > 0)  
                {  
                    UploadStatus.Text = count + " files has been uploaded.";  
                }  
            }  
            else  
            {  
                UploadStatus.Text = "Please select a file to upload.";  
            }  
        }  
    }  
} 

Output:

ASP Net Upload Multiple File 1

Select 2 files to upload.

ASP Net Upload Multiple File 2
ASP Net Upload Multiple File 3

Initially, the upload folder is empty.

ASP Net Upload Multiple File 4

Uploading files to the server.

ASP Net Upload Multiple File 5

Now, look at the upload folder. It contains uploaded two files.

ASP Net Upload Multiple File 6

ASP.NET Download File

ASP.NET provides implicit object Response and their methods to download a file from the server. We can use these methods to add the feature of downloading a file from the server to the local machine.

Here, we will create an example that allows us to download the file.

Example:

// Default.aspx
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true"   
CodeBehind="Default.aspx.cs" Inherits="FileDownload_Default" %>  
<form id="download" runat="server">  
    <p>  
        Click on the button to download a file</p>  
    <asp:Button ID="downloadButton" runat="server" OnClick="Button_Click" Text="Download" />  
    <br />  
    <br />  
    <asp:Label ID="downloadLabel" runat="server"></asp:Label>  
</form> 

Code

// Default.aspx.cs
using System;  
using System.Collections.Generic;  
using System.IO;  
using System.Linq;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
namespace FileDownloadExample  
{  
    public partial class _Default : Page  
    {  
        protected void PageLoad(object sender, EventArgs e)  
        {  
        }  
        protected void Button_Click(object sender, EventArgs e)  
        {  
            string filePath = "C:\\Users\\Admin\\Desktop\\abc.txt";  
            FileInfo file = new FileInfo(filePath);  
            if (file.Exists)  
            {  
                // Clear Rsponse reference  
                Response.Clear();  
                // Add header by specifying a file name  
                Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);  
                // Add header for content length  
                Response.AddHeader("Content-Length", file.Length.ToString());  
                // Specify content type  
                Response.ContentType = "text/plain";  
                // Clearing flush  
                Response.Flush();  
                // Transimiting file  
                Response.TransmitFile(file.FullName);  
                Response.End();  
            }  
            else Label.Text = "Requested file is not available for download";  
        }  
    }  
}  

Output:

ASP Net Downloadfile 1

The above application will prompt a window to download the file from the server.

ASP Net Downloadfile 2

Agnes Berry