Saturday, 10 September 2016

Uploading and downloading file using LinkButton in asp.net

In this article, we are going to learn how to upload and download a file using asp.net. Below is the step by step implementation of uploading and downloading file.

Related Article

  1. FileUpload control in ASP.Net

In Designer File

Step 1: In aspx file, create one FileUpload control and one Button control to upload file. Also one GridView control to display uploaded all the files and Label control to display message. Designer file look like as shown below.

uploading and downloading designer file

Below is the designer file code.

<center>
<table style="border: 1px solid black;">
<tr>
    <td colspan="2">
        <asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label>
    </td>
</tr>
<tr>
    <td>
        <asp:FileUpload ID="FileUpload1" runat="server" />
    </td>
    <td>
        <asp:Button ID="btnUpload" runat="server" Text="Upload File" OnClick="btnUpload_Click" />
    </td>
</tr>
<tr>
    <td colspan="2">
        <asp:GridView ID="grdFileUpload" runat="server" AutoGenerateColumns="False"
            OnRowCommand="grdFileUpload_RowCommand" BackColor="White" BorderColor="#999999"
            BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black" GridLines="Vertical" Width="350px">
            <AlternatingRowStyle BackColor="#CCCCCC" />
            <Columns>
                <asp:TemplateField HeaderText="File Name" >
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkDownload" runat="server" CommandArgument='<%# Eval("FileName") %>'
                            Text='<%# Eval("FileName") %>' CommandName="DownloadFile"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Size" HeaderText="File Size in Bytes" />
            </Columns>
            <FooterStyle BackColor="#CCCCCC" />
            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#808080" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#383838" />
        </asp:GridView>
    </td>
</tr>
</table>
</center>

In Code-Behind File

Step 2: Create a folder with name "FileUpload" in root directory of application.

Step 3: Add the below namespaces.

using System.Data;
using System.IO;

Step 4: Below is the code to upload a file on button click event without checking file size and file types (extension). We will simply upload a file.

protected void btnUpload_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        FileUpload1.SaveAs(Server.MapPath("~/FileUpload/" + FileUpload1.FileName));
        lblMessage.Text = "File uploaded successfully";
        DisplayGrid();
    }
    else
    {
        lblMessage.Text = "Please select a file";
    }
}

Once file is uploaded, gridview will be displaying all the files with file name and size in bytes as shown below.

uploading and downloading file in asp.net

Step 5: Below is the code to bind gridview control with file name and file size in bytes which are present in FileUpload folder.

public void DisplayGrid()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("FileName");
    dt.Columns.Add("Size");
    foreach (string file in Directory.GetFiles(Server.MapPath("~/FileUpload")))
    {
        FileInfo finfo = new FileInfo(file);
        dt.Rows.Add(finfo.Name, finfo.Length.ToString());
    }
    grdFileUpload.DataSource = dt;
    grdFileUpload.DataBind();
}

Step 6: Below is the code to download a file from FileUpload folder using GridView RowCommand event and CommandArgument event of LinkButton control.

protected void grdFileUpload_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "DownloadFile")
    {
        Response.Clear();
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", "filename=" + e.CommandArgument);
        Response.TransmitFile(Server.MapPath("~/FileUpload/") + e.CommandArgument);
        Response.End();
    }
}

Complete C# Code

Complete code snippet given below.

using System;
using System.Collections.Generic;
using System.Data; // namespaces added
using System.IO;  // namespaces added
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DisplayGrid();
            }
        }
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                FileUpload1.SaveAs(Server.MapPath("~/FileUpload/" + FileUpload1.FileName));
                lblMessage.Text = "File uploaded successfully";
                DisplayGrid();
            }
            else
            {
                lblMessage.Text = "Please select a file";
            }
        }
        public void DisplayGrid()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("FileName");
            dt.Columns.Add("Size");
            foreach (string file in Directory.GetFiles(Server.MapPath("~/FileUpload")))
            {
                FileInfo finfo = new FileInfo(file);
                dt.Rows.Add(finfo.Name, finfo.Length.ToString());
            }
            grdFileUpload.DataSource = dt;
            grdFileUpload.DataBind();
        }
        protected void grdFileUpload_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "DownloadFile")
            {
                Response.Clear();
                Response.ContentType = "application/octet-stream";
                Response.AppendHeader("Content-Disposition", "filename=" + e.CommandArgument);
                Response.TransmitFile(Server.MapPath("~/FileUpload/") + e.CommandArgument);
                Response.End();
            }
        }    
    }
}
Share:

3 comments:

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

BUY FROM AMAZON

Ads By Chitika