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

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):

pdftable.png

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,
  1. <form id="form1" runat="server">  
  2.     <div>  
  3.         <table>  
  4.             <tr>  
  5.                 <td> Select File </td>  
  6.                 <td>  
  7.                     <asp:FileUpload ID="FileUpload1" runat="server" ToolTip="Select Only Excel File" /> </td>  
  8.                 <td>  
  9.                     <asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" /> </td>  
  10.                 <td>  
  11.                     <asp:Button ID="Button2" runat="server" Text="View Files" onclick="Button2_Click" /> </td>  
  12.             </tr>  
  13.         </table>  
  14.         <table>  
  15.             <tr>  
  16.                 <td>  
  17.                     <p>  
  18.                         <asp:Label ID="Label2" runat="server" Text="label"></asp:Label>  
  19.                     </p>  
  20.                 </td>  
  21.             </tr>  
  22.         </table>  
  23.         <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">  
  24.             <RowStyle BackColor="#E3EAEB" />  
  25.             <Columns>  
  26.                 <asp:CommandField ShowSelectButton="True" SelectText="Download" ControlStyle-ForeColor="Blue" /> </Columns>  
  27.             <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />  
  28.             <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />  
  29.             <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />  
  30.             <HeaderStyle BackColor="Gray" Font-Bold="True" ForeColor="White" />  
  31.             <EditRowStyle BackColor="#7C6F57" />  
  32.             <AlternatingRowStyle BackColor="White" /> </asp:GridView>  
  33.     </div>  
  34. </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.

  1. protected void Button1_Click(object sender, EventArgs e) {  
  2.     Label2.Visible = true;  
  3.     string filePath = FileUpload1.PostedFile.FileName; // getting the file path of uploaded file  
  4.     string filename1 = Path.GetFileName(filePath); // getting the file name of uploaded file  
  5.     string ext = Path.GetExtension(filename1); // getting the file extension of uploaded file  
  6.     string type = String.Empty;  
  7.     if (!FileUpload1.HasFile) {  
  8.         Label2.Text = "Please Select File"//if file uploader has no file selected  
  9.     } else  
  10.     if (FileUpload1.HasFile) {  
  11.         try {  
  12.             switch (ext) // this switch code validate the files which allow to upload only PDF file   
  13.             {  
  14.                 case ".pdf":  
  15.                     type = "application/pdf";  
  16.                     break;  
  17.             }  
  18.             if (type != String.Empty) {  
  19.                 connection();  
  20.                 Stream fs = FileUpload1.PostedFile.InputStream;  
  21.                 BinaryReader br = new BinaryReader(fs); //reads the binary files  
  22.                 Byte[] bytes = br.ReadBytes((Int32) fs.Length); //counting the file length into bytes  
  23.                 query = "insert into PDFFiles (Name,type,data)" + " values (@Name, @type, @Data)"//insert query  
  24.                 com = new SqlCommand(query, con);  
  25.                 com.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename1;  
  26.                 com.Parameters.Add("@type", SqlDbType.VarChar).Value = type;  
  27.                 com.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;  
  28.                 com.ExecuteNonQuery();  
  29.                 Label2.ForeColor = System.Drawing.Color.Green;  
  30.                 Label2.Text = "File Uploaded Successfully";  
  31.             } else {  
  32.                 Label2.ForeColor = System.Drawing.Color.Red;  
  33.                 Label2.Text = "Select Only PDF Files "// if file is other than speified extension   
  34.             }  
  35.         } catch (Exception ex) {  
  36.             Label2.Text = "Error: " + ex.Message.ToString();  
  37.         }  
  38.     }  
  39. }  

Add the following code in the view file button click to View uploaded PDF files in GridView

  1. protected void Button2_Click(object sender, EventArgs e) {  
  2.     connection();  
  3.     query = "Select *from PDFFiles";  
  4.     SqlDataAdapter da = new SqlDataAdapter(query, con);  
  5.     DataSet ds = new DataSet();  
  6.     da.Fill(ds);  
  7.     GridView1.DataSource = ds;  
  8.     GridView1.DataBind();  
  9.     con.Close();  
  10. }  

Add the following code to the Gridview selected index changed event to download the files,

  1. protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) {  
  2.     connection();  
  3.     SqlCommand com = new SqlCommand("select Name,type,data from PDFFiles where id=@id", con);  
  4.     com.Parameters.AddWithValue("id", GridView1.SelectedRow.Cells[1].Text);  
  5.     SqlDataReader dr = com.ExecuteReader();  
  6.     if (dr.Read()) {  
  7.         Response.Clear();  
  8.         Response.Buffer = true;  
  9.         Response.ContentType = dr["type"].ToString();  
  10.         Response.AddHeader("content-disposition""attachment;filename=" + dr["Name"].ToString()); // to open file prompt Box open or Save file  
  11.         Response.Charset = "";  
  12.         Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  13.         Response.BinaryWrite((byte[]) dr["data"]);  
  14.         Response.End();  
  15.     }  
  16. }  

Then run the page which will look as in the following,

demoscreen.png

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:

validatate.png

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

Uploaded.png

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

filesList.png

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

Savefiles.png

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.

Div tables are great to layout website sections on the page!

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now