Sunteți pe pagina 1din 6

7/7/13

Uploading and Downloading PDF Files From Database Using ASP.NET C#

In Focus

C# Corner Mumbai Chapter: WPF Hands On

Ask a Question
TECHNOLOGIES ANSWERS BLOGS VIDEOS INTERVIEWS BOOKS LINKS NEWS CHAPTERS CAREER ADVICE

Contribute

Locate Mobile Number Using JavaScript in ASP.Net

C# Corner Search

PREMIUM SPONSORS

ARTICLE
75 1,542

Nevron
Nevron Software is a global leader in component based data visualization technology for a diverse range of Microsoft centric platforms. Nevron Data Visualization components are used by many companies, educational and government organizations around the world.

Uploading and Downloading PDF Files From Database Using ASP.NET C#


Posted by Vithal Wadje in Articles | Web Development on December 28, 2012 Tags: ASP.NET, C#, Database Using ASP.NET C#, Downloading PDF Files, Uploading PDF Files In this article I will explain how to upload only PDF files with validation to a database and display in a gridview and download the PDFl files from a database on the gridview selected event.

Tw eet

Share

Like

10

21082

Reader Level:

Download Files: PDFFileUploadDownLoad.zip


Background Many times their is a need in a project's reporting module to upload and download the specific types of files with restrictions; I am also working with these types of modules, so I want to share my experience to others so they can benefit from this aricle when they encounter the same type of task. So by considering the above requirement I decided to write this article especially focusing on beginners and those who want to learn how to upload only PDF files and display in a grid view and download files in a gridview selected event which is displayed in the grid view. Now before creating the application, let us create a table named PDFFiles in a database to store the Uploaded PDF files in a database table having the following fields (shown in the following image):

TRENDING UP
Locate Mobile Number Using JavaScript in ASP.Net Learn OOP Interface Using C# How the URL and URLConnection Classes Work In Java How to Add an Alias (CNAME) Resource Record to a Zone Logging Using Log4net in Compact Framework 2.0 in Visual Studio 2008 JsAction with T4 Template How To Find A Doctor Near Your Home in SQL Server Rhino MockRepository Concrete vs Static Usage How to Set Image in a Image View on Click in Android Studio XML Parser Function in PHP: Part 3

In the above table I have created four columns, they are id for the unique identity, Name for the PDF file name, type for file type and data to store the actual content of the files with binary datatype because the content of the files stored in bytes. I hope you have created the same type of table. Now let us start to create an application to upload and download PDF files step-by-step. Now create the project as: 1. "Start" - "All Programs" - "Microsoft Visual Studio 2010". 2. "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page). 3. Give the Project name such as PDFFileUploadDownload or another as you wish and specify the location. 4. Then right-click on Solution Explorer - "Add New Item" - Default.aspx page. 5. one File upload control, two Buttons, one label and a grid view. Then the <form> section of the Default aspx page looks as in the following: <form id="form1" runat="server"> <div> <table> <tr> <td> Select File </td> <td> <asp:FileUpload ID="FileUpload1" runat="server" ToolTip="Select Only Excel File" /> </td> <td> <asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" /> </td> <td>

View All

MOST LIKED ARTICLE


WCF Introduction and Contracts - Day 1 Create SSRS Report Using Report Wizard CREATE READ UPDATE and DELETE - CRUD Operation Using LINQ to SQL WCF - Data Contract - Day 4 Factory Design Pattern
Follow @csharpcorner Find us on Facebook 4,736 follow ers

C# Corner
Like 12,383 people like C# Corner.

F acebook social plugin

HOT KEYWORDS
1/6

www.c-sharpcorner.com/UploadFile/0c1bb2/uploading-and-downloading-pdf-files-from-database-using-asp/

7/7/13

Uploading and Downloading PDF Files From Database Using ASP.NET C#


<asp:Button ID="Button2" runat="server" Text="View Files" onclick="Button2_Click" /> </td> </tr> .NET Classes .NET components ASP.NET Page Execution Display File stream HTTP handler MasterDetailedDisplay MemoryStream using a HTTP Handler Migration Modal Popup Modal Popup Dialog Window Modal Popup Dialog Window in ASP.NET Page directive Planning Popup

</table> <table><tr><td><p><asp:Label ID="Label2" runat="server" Text="label"></asp:Label> </p></td></tr> </table> <asp:GridView ID="GridView1" runat="server" Caption="Excel Files " CaptionAlign="Top" HorizontalAlign="Justify" DataKeyNames="id" onselectedindexchanged="GridView1_SelectedIndexChanged" ToolTip="Excel FIle DownLoad Tool" CellPadding="4" ForeColor="#333333" GridLines="None"> <RowStyle BackColor="#E3EAEB" /> <Columns> <asp:CommandField ShowSelectButton="True" SelectText="Download" ControlStyle-ForeColor="Blue"/> </Columns> <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" /> <HeaderStyle BackColor="Gray" Font-Bold="True" ForeColor="White" /> <EditRowStyle BackColor="#7C6F57" /> <AlternatingRowStyle BackColor="White" /> </asp:GridView> </div> </form> Now switch to design mode and double-click on the upload button and put the following code to upload and validate that only PDF files are allowed to be upload. protected void Button1_Click(object sender, EventArgs e) { Label2.Visible = true; string filePath = FileUpload1.PostedFile.FileName; string filename1 = Path.GetFileName(filePath); string ext = Path.GetExtension(filename1); string type = String.Empty;

Posting data from ASP.NET page to another URL RemotePost Class render
Window PostBackData

Shopping Cart Shopping Cart Application in ASP.NET


tic tac toe game web form Web.config file Windows Users

SPONSORED BY
Get the industry leading .NET Diagramming component
.NET Diagramming framework designed for creating advanced solutions

// getting the file path of uploaded file // getting the file name of uploaded file // getting the file extension of uploaded file

if (!FileUpload1.HasFile) { Label2.Text = "Please Select File"; } else if (FileUpload1.HasFile) { try { switch (ext) {

//if file uploader has no file selected

WHITEPAPERS AND BOOKS


Interview Questions on SharePoint 2013 SharePoint 2010 Administration & Development Getting Started with Managed Metadata Service in SharePoint 2010

PDF file

// this switch code validate the files which allow to upload only

Windows Phone 7 Hileleri Windows Phone Development Step by Step Tutorial Essentials of SharePoint 2010: Business Intelligence Capabilities Working with Directories in C# FileInfo in C# Programming List with C# Source Code: Graphics Programming with GDI+

case ".pdf": type = "application/pdf"; break;

} if (type != String.Empty) { connection(); Stream fs = FileUpload1.PostedFile.InputStream; BinaryReader br = new BinaryReader(fs); //reads the binary files Byte[] bytes = br.ReadBytes((Int32)fs.Length); //counting the file length into bytes query = "insert into PDFFiles (Name,type,data)" + " values (@Name, @type, @Data)"; //insert query com = new SqlCommand(query, con); com.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename1; com.Parameters.Add("@type", SqlDbType.VarChar).Value = type; com.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes; com.ExecuteNonQuery(); Label2.ForeColor = System.Drawing.Color.Green; Label2.Text = "File Uploaded Successfully"; } else { Label2.ForeColor = System.Drawing.Color.Red; Label2.Text = "Select Only PDF Files "; // if file is other than speified extension }

View All
POLL RESULT ALL POLLS

Speed of C# Corner

How do you find speed of C# Corner when visiting the site? Very Fast OK Slow Very Slow
Vote

} catch (Exception ex) { Label2.Text = "Error: " + ex.Message.ToString(); }

www.c-sharpcorner.com/UploadFile/0c1bb2/uploading-and-downloading-pdf-files-from-database-using-asp/

2/6

7/7/13

Uploading and Downloading PDF Files From Database Using ASP.NET C#

Add the following code in the view file button click to View uploaded PDF files in GridView protected void Button2_Click(object sender, EventArgs e) { connection(); query = "Select *from PDFFiles"; SqlDataAdapter da = new SqlDataAdapter(query, con); DataSet ds = new DataSet(); da.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); con.Close(); } Add the following code to the Gridview selected index changed event to download the files: protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { connection(); SqlCommand com =new SqlCommand("select Name,type,data from PDFFiles where id=@id", con); com.Parameters.AddWithValue("id", GridView1.SelectedRow.Cells[1].Text); SqlDataReader dr = com.ExecuteReader();

if (dr.Read()) { Response.Clear(); Response.Buffer =true; Response.ContentType = dr["type"].ToString(); Response.AddHeader("content-disposition", "attachment;filename=" + dr["Name"].ToString()); open file prompt Box open or Save file Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.BinaryWrite((byte[])dr["data"]); Response.End(); } } Then run the page which will look as in the following:

// to

From the above view I am using two buttons to do the upload; one to upload the selected files to the database and view files which shows the files in a grid view which is stored in a database table. Now run the application and select the file other than PDF which shows the following error as shown in the following:

www.c-sharpcorner.com/UploadFile/0c1bb2/uploading-and-downloading-pdf-files-from-database-using-asp/

3/6

7/7/13

Uploading and Downloading PDF Files From Database Using ASP.NET C#

Now select the PDF file, which shows the following message after being successfully uploaded:

Now click on view files details. The gridview shows the uploaded files with details as shown below.

Now click on the download button of the gridview, the following prompt message is displayed as shown in

following image:

www.c-sharpcorner.com/UploadFile/0c1bb2/uploading-and-downloading-pdf-files-from-database-using-asp/

4/6

7/7/13

Uploading and Downloading PDF Files From Database Using ASP.NET C#

Then choose browse with Adobe Reader and click on the ok button. Then the file will be opened in PDF format .
Summary

I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also. Note Download the zip file from the attachment for the full source code of an application.
Login to add your contents and source code to this article

Article Extensions
Contents added by anass majidi on Jun 27, 2013 Contents added by prem choudhary on May 25, 2013

THIS FEATURE IS SPONSORED BY

.NET Di a gra mmi ng fra mework des i gned for crea ti ng a dva nced s ol uti ons

Uploading and Downloading Word Files From Database Using ASP.NET C#


Tags: ASP.NET, C#, Database Using ASP.NET C#, Downloading Word Files, Uploading Word Files

Tags: insert data into database in asp.net C#, Inserting form data into database, inserting form data using stored procedure

Inserting Form Data Into DataBase Using Stored Procedure In ASP.NET C#

RELATED ARTICLES
Operations of CSV Files and Text Files Using C# ASP.NET HJ PDF in C# How to handle multiple file upload dynamically Download / Upload Binary Files on FTP Server Using C# File Uploading in ASP.NET 2.0 Uploading and Downloading Excel Files From Database Using ASP.NET C# How to download a file in ASP.Net Upload and Download File From Database Using GridView How to Upload Files in ASP.NET Uploading Multiple Files Using Flash in ASP.Net

COMMENTS
6 of 6 Prachi Chandrakar Thank you so much really helpful tutorial. :)
0 Li ke 0 Repl y

Jan 02, 2013

Vithal Wadje thanx prachi


0 Li ke 0 Repl y

Jan 02, 2013

sankeerth thanx and can you give me code for upload and download pdfs which is of large size for example pdf length is 20mb in c# and asp.net using database.please provide me result as early as possible
0 Li ke 0 Repl y

Mar 20, 2013

www.c-sharpcorner.com/UploadFile/0c1bb2/uploading-and-downloading-pdf-files-from-database-using-asp/

5/6

7/7/13

Uploading and Downloading PDF Files From Database Using ASP.NET C#


rain boy your totorial help me but where column name and type for input value
0 Li ke 0 Repl y
May 08, 2013

Tony Pitwood Unable to upload - hits error: Error: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) In Connection, constr = "Data Source=datasourcename;Initial Catalog=databasename;User ID=username;Password=sqlpassword" Should this not have values instead?
0 Li ke 0 Repl y

May 13, 2013

Vithal Wadje your connection string in web.config is wrong first make it perfect
0 Li ke 0 Repl y

May 15, 2013

Type your comment here and press Enter Key....

COMMENT USING
6 comments Abdul Alim Comilla Victoria Govt. College thanks Reply 1 Like Follow Post May 19 at 12:06am Add a comment

Samah Qandeel Works at FCI Helwan thnxx Reply Like Follow Post June 16 at 4:57am Suresh Rajpurohit Follow Rajasthan technical university 'vit jaipur'

good material of asp.net about database handling....but missing threee query(1)ExecuteNonQurey (2)ExecutrReader. (3)ExecuteScalar method with example.... fast please sir. Reply Like Follow Post May 2 at 3:06pm Oyebisi Jemil Lautech'14 nice one Reply Like Follow Post May 6 at 4:28am Daniel Oliveira Instituto Federal da Bahia - IFBA the code does not work with internet explorer. Reply Like Follow Post May 24 at 6:26pm View 1 more
F acebook social plugin

MVPs

MOST VIEWED

LEGENDS

NOW

PRIZES

AWARDS

REVIEWS

SURVEY

CERTIFICATIONS

DOWNLOADS

Hosted By CBeyond Cloud Services

PHOTOS

TIPS

CONSULTING

TRAINING

STUDENTS

MEMBERS

MEDIA KIT

SUGGEST AN IDEA

PRIVACY POLICY | TERMS & CONDITIONS | SITEMAP | CONTACT US | ABOUT US | REPORT ABUSE

2013 C# Corner. All contents are copyright of their authors.

www.c-sharpcorner.com/UploadFile/0c1bb2/uploading-and-downloading-pdf-files-from-database-using-asp/

6/6

S-ar putea să vă placă și