Upload PDF File and Open it in Browser

Raj.Trivedi
Posted by in ASP.NET category on for Beginner level | Points: 250 | Views : 8392 red flag

Hello Team, In this article we will see how to upload a PDF File and bind it to the gridview and Open it in the Browser itself

Introduction

There are lot of times where we will require to upload documents in PDF Format in our web application and open it in the browser.

Over here in this article we will see how to upload the PDF and bind the File path to the Gridview an Open the PDF in the Browser

Objective

  1. To Upload PDF in a Folder and Save the Path to the database
  2. Bind the Path in the Gridview 
  3. To Open the PDF in the Browser

Using the code


  1. Create a New Empty Website in Visual Studio 2010
  2. Add a Web form in the Website and a Web Config file
  3. Now right click on the Website Name and Create a Folder named as PDFS to store the PDF Files that we are uploading
Your Solution Explorer will be as shown in the screen





  1. Now drag and Drop a File Uploader and a Button on the Webform
  2. Also drag and drop a Grid View on the Web Page.
  3. Now click on the Arrow of the Grid View go to the Item Template and add a Link Button in the Item Template
  4. Drag and Drop a Label on the page for the status.
  5. Now go to the Gridview and inside the Item Template add a CommandName as "View" and Command Arguement as '<%#Eval("pdfpath") %>' 
  6. The Command Arguement is the column name of the database where the path is stored.
  7. Check the HTML mark up for adding Command Arguement and Command Name.
  8. Also add a Name space for System.IO for input and output Operations
Adding Item Template



Your Web Page will look like this.









// HTML Mark up and Code behind
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadandViewPDF.aspx.cs" Inherits="UploadandViewPDF" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   
<title></title>
   
<style type="text/css">
       
.style1
       
{
            width
: 100%;
       
}
       
.style2
       
{
            width
: 134px;
       
}
       
.style3
       
{
            width
: 217px;
       
}
   
</style>
</head>
<body>
   
<form id="form1" runat="server">
   
<div>
   
       
<table class="style1">
           
<tr>
               
<td class="style2">
                    Browse PDF
</td>
               
<td class="style3">
                   
<asp:FileUpload ID="fupdf" runat="server" />
               
</td>
               
<td>
                    &nbsp;
</td>
           
</tr>
           
<tr>
               
<td class="style2">
                    &nbsp;
</td>
               
<td class="style3">
                   
<asp:Button ID="btnUpload" runat="server" Text="Upload and Save"
                       
onclick="btnUpload_Click" />
               
</td>
               
<td>
                    &nbsp;
</td>
           
</tr>
           
<tr>
               
<td class="style2">
                    &nbsp;
</td>
               
<td class="style3">
                   
<asp:Literal ID="xlitdesc" runat="server"></asp:Literal>
               
</td>
               
<td>
                    &nbsp;
</td>
           
</tr>
           
<tr>
               
<td class="style2">
                    &nbsp;
</td>
               
<td class="style3">
                    &nbsp;
</td>
               
<td>
                    &nbsp;
</td>
           
</tr>
       
</table>
   
   
</div>

   
<br />
   
<br />
   
<div>
       
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
           
onrowcommand="GridView1_RowCommand">
           
<Columns>
               
<asp:BoundField DataField="id" HeaderText="ID" />
               
<asp:TemplateField HeaderText="Open File">
                   
<ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" CommandName="view" CommandArgument='
<%#Eval("pdfpath") %>' runat="server">LinkButton</asp:LinkButton>
                   
</ItemTemplate>
               
</asp:TemplateField>
           
</Columns>
       
</asp:GridView>
   
</div>

   
</form>
</body>
</html>                                                                                                                                                                                                                                                                                         CCode Behind                                                                                                                                                                                                                                                                                    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.IO;
using System.Data.SqlClient;


public partial class UploadandViewPDF : System.Web.UI.Page
{
    string strconn = ConfigurationManager.ConnectionStrings["cnnLocal"].ConnectionString;
    string desc = "0";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            if (fupdf.HasFile)
            {
                string extension = Path.GetExtension(fupdf.FileName);
                string filename = Path.GetFileName(fupdf.FileName);
                string uploadFolder = Request.PhysicalApplicationPath + "PDFS\\"; // This will get the actual path for upload.
                string upload = "~/PDFS/" + filename;   // This path will go in database because asp.net requires virtual path.
                fupdf.SaveAs(uploadFolder + filename);
                string getfile = upload;
                SqlConnection con = new SqlConnection(strconn);
                SqlCommand cmdins = new SqlCommand("savepdf", con);
                cmdins.CommandType = CommandType.StoredProcedure;
                cmdins.Parameters.AddWithValue("@pdfpath", getfile);
                con.Open();
                cmdins.ExecuteNonQuery();
                xlitdesc.Text = "Data Saved";
                BindGrid();
            }
        }
        catch (Exception ex)
        {
            xlitdesc.Text = ex.Message;
        }
   
    }

        private void BindGrid()
        {
            try
            {
                SqlConnection con = new SqlConnection(strconn);
                con.Open();
                SqlCommand cmdins = new SqlCommand();
                cmdins.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand("ShowGrid", con);
                DataSet ds = new DataSet();
                da.Fill(ds, "pdffiles");
                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
            catch (Exception ex)
            {
               desc =  ex.Message;
            }
       
        }




        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
             switch (e.CommandName)
            {
            case "view":
            string filename = e.CommandArgument.ToString();
            string path = MapPath(filename);
            byte[] bts = System.IO.File.ReadAllBytes(path);
            Response.Clear();
            Response.ClearHeaders();
            Response.ContentType = "application/pdf";
            Response.WriteFile(path);
            Response.Flush();
            Response.End();
            break;
                }
            }
            catch(Exception ex)
            {
                desc = ex.Message;

            }
        }
}
 


Output Screen 1 :- 


After you click on the View/Download Link Button the PDF File will be opened in the Browser.


Output Screen 2 :- Viewing PDF






Conclusion


Hope this will be a Nice Resource........
Love to Share.....
Page copy protected against web site content infringement by Copyscape

About the Author

Raj.Trivedi
Full Name: Raj Trivedi
Member Level:
Member Status: Member,MVP
Member Since: 6/16/2012 2:04:41 AM
Country: India
Regard's Raj.Trivedi "Sharing is Caring" Please mark as answer if your Query is resolved
http://www.dotnetfunda.com/profile/raj.trivedi.aspx
Raj Trivedi i.e. me started my career as Support Professional and then moved on the Software development eventually reached at these skills Software Development | Enthusiastic Blogger | Content Writer | Technical Writer | Problem Solver | Lecturer on Technology Subjects | Runnerup Award Winner on www.dotnetfunda.com and firm believer in Sharing as a way of Caring Yet this much achieved its still a long way to go and there is biggest dream lying to be one of the best entrepreneurs of India in Technology Department. The Dream has just started and i hope it follows. Highlights are mentioned in details in my profile at http://in.linkedin.com/pub/raj-trivedi/30/61/b30/

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)