[Solved] - How Upload and Download PDF file Database in ASP.Net?


In today's digital age dominated by the internet, computers, and smartphones, many tasks that were once manual are now performed digitally. Whether it's creating projects or preparing files, the computer has become central to these processes. Saving documents digitally allows for easy sharing via email, with PDF files being particularly popular for this purpose.

Recently, I've been working on a project that involves uploading PDF files to a database and enabling users to download them. Recognizing the value of sharing knowledge with fellow developers, I've decided to document the process in an article, especially beneficial for beginners.

The task at hand involves uploading PDF files to a database table, displaying them in a grid view, and providing users with the capability to download these files. To facilitate this, I've set up a table dedicated to storing the uploaded files.

 

Database Script

CREATE TABLE [dbo].[PdfFiles](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [FileName] [varchar](200) NOT NULL,
    [FileData] [varbinary](max) NOT NULL,
    [ContentType] [varchar](200) NOT NULL,
 CONSTRAINT [PK_PdfFiles] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

 

Html Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Index.aspx.cs" Inherits="Index" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:FileUpload ID="FileUpload1" runat="server" ToolTip="Select Only Excel File" />
            <br />
            <br />
            <asp:Button ID="Button1" runat="server" Text="Upload Pdf" OnClick="Button1_Click" />
            <br />
            <br />
            <asp:GridView ID="PdfGridView" runat="server" Caption="PdfFiles" CaptionAlign="Top" HorizontalAlign="Justify" DataKeyNames="id" ToolTip="Pdf FIle DownLoad Tool" CellPadding="4" ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="PdfGridView_SelectedIndexChanged">
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <Columns>
                    <asp:CommandField ShowSelectButton="True" SelectText="Download" ControlStyle-ForeColor="Blue">
                        <ControlStyle ForeColor="Blue"></ControlStyle>
                    </asp:CommandField>
                </Columns>
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <EditRowStyle BackColor="#999999" />
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            </asp:GridView>
        </div>
    </form>
</body>
</html>

As you can see in the above code I have a grid view control. After uploading the pdf files I’m display the all files in this gridview control with the download link. On SelectedIndexChanged event we are downloading the pdf files.

C# Code

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Index : System.Web.UI.Page
{
    string constr = "Data Source=SQLEXPRESS01;Initial Catalog=DemoDataBase;User ID=sa;Password=sa@1234"; 
    //your database connection string
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDataGrid();
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            string Pdffilename = Path.GetFileName(FileUpload1.PostedFile.FileName);
            string contentType = FileUpload1.PostedFile.ContentType;
            using (Stream fs = FileUpload1.PostedFile.InputStream)
            {
                using (BinaryReader br = new BinaryReader(fs))
                {
                    byte[] bytes = br.ReadBytes((Int32)fs.Length);
                    
                    using (SqlConnection con = new SqlConnection(constr))
                    {
                        //inserting data into database
                        string query = "insert into PdfFiles values (@FileName, @FileData, @ContentType)";
                        using (SqlCommand cmd = new SqlCommand(query))
                        {
                            cmd.Connection = con;
                            cmd.Parameters.AddWithValue("@FileName", Pdffilename);
                            cmd.Parameters.AddWithValue("@FileData", bytes);
                            cmd.Parameters.AddWithValue("@ContentType", contentType);
                            con.Open();
                            cmd.ExecuteNonQuery();
                            con.Close();
                        }
                    }
                }
            }
            Response.Redirect(Request.Url.AbsoluteUri);
        }
        catch (Exception ex)
        {

        }
    }
    private void BindDataGrid()
    {
        //binding data in gridview
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "Select *from PDFFiles";
                cmd.Connection = con;
                con.Open();
                PdfGridView.DataSource = cmd.ExecuteReader();
                PdfGridView.DataBind();
                con.Close();
            }
        }
    }
    protected void PdfGridView_SelectedIndexChanged(object sender, EventArgs e)
    {
        //downloading the pdf files from database
        int id =Convert.ToInt32(PdfGridView.SelectedRow.Cells[1].Text);
        byte[] bytes;
        string fileName, contentType;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select FileName, FileData, ContentType from PdfFiles where Id=@Id";
                cmd.Parameters.AddWithValue("@Id", id);
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    sdr.Read();
                    bytes = (byte[])sdr["FileData"];
                    contentType = sdr["ContentType"].ToString();
                    fileName = sdr["FileName"].ToString();
                }
                con.Close();
            }
        }
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = contentType;
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
        Response.BinaryWrite(bytes);
        Response.Flush();
        Response.End();
    }
}

Download Source Code

Result


This C# code in ASP.NET web application that allows users to upload PDF files to a database, display them in a GridView, and download selected files.


Button1_Click Event Handler:

  • This event handler is triggered when Button1 is clicked, likely representing a button for uploading a PDF file.
  • It retrieves the filename, content type, and binary data of the uploaded file.
  • It establishes a connection to the database, prepares an SQL INSERT statement, and executes it with parameters for filename, file data, and content type.
  • Finally, it redirects the user back to the current page after the upload is completed.
BindDataGrid Method:

  • This method is responsible for populating a GridView control with data from the database.
  • It establishes a connection to the database, prepares an SQL SELECT statement to fetch all data from the PdfFiles table, executes the query, and binds the results to the GridView.
PdfGridView_SelectedIndexChanged Event Handler:

  • This event handler is triggered when a row in the GridView (presumably displaying PDF files) is selected.
  • It retrieves the ID of the selected row and uses it to fetch corresponding file data from the database.
  • The file data (bytes), filename, and content type are extracted from the SqlDataReader.
  • Response headers are set to specify the content type and filename for the browser.
  • The file data is written to the response stream, prompting the browser to download the file.
Above code allows users to upload PDF files, stores them in a database, displays them in a GridView, and enables users to download selected PDF files. However, it's important to note that this code is susceptible to SQL injection attacks due to the direct use of user inputs in SQL queries without proper validation or parameterization. Additionally, error handling in the catch block of Button1_Click should be improved to provide meaningful feedback to users and handle exceptions appropriately.