As you know, today’s era is the internet, computer, and smartphone. Earlier, the work we used to do manually is done on the computer. You have to make any project or prepare a file, you save it by typing it on the computer and then take a print out of it, you can easily share such digital files with anyone through email. As you that Pdf files are very popular for this purpose.So, I am working on a project where I have a requirement in which I have to create a pdf file.
Basically, my task is that I need to upload the pdf in the database, and then the user should be able to download it.So that I decided to share my code with other developers so that they can benefit from this code whenever they facing the same type of requirement.

So I decided to write an article on these points which will help for the beginners.

Task-How to upload PDF files in a database table and display in a grid view and  Download the Pdf Files.

For that, i have created a table for 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

The post [Solved]-How Upload and Download PDF file Database in ASP.Net? appeared first on Software Development | Programming Tutorials.



Read More Articles