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):
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:
- "Start" - "All Programs" - "Microsoft Visual Studio 2010".
- "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).
- Give the Project name such as PDFFileUploadDownload or another as you wish and specify the location.
- Then right-click on Solution Explorer - "Add New Item" - Default.aspx page.
- 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>
- <asp:Button ID="Button2" runat="server" Text="View Files" onclick="Button2_Click" /> </td>
- </tr>
- </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;
- if (!FileUpload1.HasFile) {
- Label2.Text = "Please Select File";
- } else
- if (FileUpload1.HasFile) {
- try {
- switch (ext)
- {
- case ".pdf":
- type = "application/pdf";
- break;
- }
- if (type != String.Empty) {
- connection();
- Stream fs = FileUpload1.PostedFile.InputStream;
- BinaryReader br = new BinaryReader(fs);
- Byte[] bytes = br.ReadBytes((Int32) fs.Length);
- query = "insert into PDFFiles (Name,type,data)" + " values (@Name, @type, @Data)";
- 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 ";
- }
- } catch (Exception ex) {
- Label2.Text = "Error: " + ex.Message.ToString();
- }
- }
- }
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());
- 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,
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:
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:
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!