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.
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();
}
}
Result
The post [Solved]-How Upload and Download PDF file Database in ASP.Net? appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- How Can I Extend the maximum file size to upload and send (via email) files while using jquery.MultiFile.js
- Using Azure Function .NET5 and HttpRequestData, how to handle file upload (form data)?
- how to use ssl certificates with gRPC and ASP Net Core 3.0?
- How to merge .pdf and .jpg file in one pdf
- How to upload video in ASP.NET MVC 5 and pass the video file from a view to a method?
- Multiple image uploads through file upload and saving to database asp.net
- Net Core: How to Simple Unit Test Repository and Service with Database Rows
- How to download and run a .exe file c#
- File Upload and Download using Asp.net
- How can I download a file using WebClient in C# with firing the eventhandlers and supporting the timeout property?
- How upload csv file and parse it?
- How to stream file upload in C# Web Api for database storage
- how to download a xls file generated by NPOI in ASP MVC
- Backup a database using c#, the bak file gets bigger and bigger, how do I stop it from growing?
- How to download .xslx File from server using EPPlus and MVC
- How do I generate a PDF/Excel file from an SQL database using C# and MVC 2?
- How to programatically execute and export .rdl file to pdf without any SSRS and reportviewer
- How to enrich azure b2c token with custom claims using api connectors and asp net core web api
- How to download and open XML file via SFTP?
- How To Get Sql Database Backup File's Data and Log File Paths Using SMO in C#
- How to add item into window's Context menu [only for pdf file and doc file]
- How to capture and convert textbox into pdf file format?
- ASP.NET MVC - How to upload an image and save URL in the database
- How to convert data to pdf files and then insert to zip and download it
- How to do encrypting and decrypting pdf file in c#?
- How to Upload Excel file and convert that to Google spreadsheet programmatically?
- How to convert the ASP.NET pages as PDF and download the same(values are not static)
- How to read from database and write into text file with C#?
- How can I (properly) verify a file using RSA and SHA256 with .NET?
- how to display G map by repeater and markers from database
- Change datetime to date in MVC 3 C#
- Dynamically loading and unloading a a dll generated using CSharpCodeProvider
- How to get processID from Process.start()
- Instantiating a Prefab Without Inheriting Monobehaviour
- Programmatically edit IIS IPGrant Table
- Using extended ASCII to create a tree in a WinForms RichTextBox control
- StructureMap, scan assemblies and scoping
- How should i register generic interfaces in .NET Core 2.2
- Unit testing Void method which calls another void, starts Task()
- Calling Drillthrough report in rdlc
- Gaze Over, display Tooltip in Unity with GoogleVR
- Using Wildcard in C# to get the string of a dynamic generated file?
- Strange behaviour when get current month in C#
- Other Ways To Code Side By Side Enumeration?
- In Metro, how do I get a list of all countries?
- Arithmetic operation not returning the same in VB6 and C#
- What is the best practice concerning overload
- How to prevent simultaneous login with same user on different pcs
- C# What is the easiest way to disable a control after 10 seconds? Timer or stopwatch?
- Learning WPF without success