Upload Files And Save In Oracle Database In Blob Format In ASP.NET

Overview

Today, we will see how to upload files, whether it's a Word file, pdf, zip files etc., and save them in the Oracle database as well as retrieve those files and download those. This code is useful when you need to upload various documents in an organization, including process documents, news and so on. Other users will have to download those files and see the contents. To see the content of what you have uploaded, you have to save it in Binary format. Let's start: 

uploaded

Step 1 : Lets create a table first

First, you need to install the Oracle Database on your machine and create databases in your system. The Oracle SQL Developer is a GUI to access those databases.

Once you are through with the installation and creation of the database, it is time to add a connection.

Note:

Before installing Oracle, you need to add TNS names in tnsnames.ora in order to communicate with your databases.

Go to your system drive where you had installed the Oracle. This is my path: 

path

Open tnsname.ora file and add a TNS entry there.

code

Now, configure the connection in your Oracle SQL Developer.

SQL

Click on Connect. It will add a connection successfully. We have connected to our database successfully .

database

Now, let's create a table.

table

Look at the Data type in Oracle carefully. I made ID as primary key. Oracle doesn’t identify the GUI. So, you have to write a query for this .

The name I gave is Varchar2 with a length of 4000 Bytes (maximum). 
Content type is again varchar2 which is again 4000 Bytes long (maximum).

Data is stored in BLOB. ( Remember in the previous article in SQL server we had been storing data in Binary Format). Here, in Oracle,  we will be saving Data in BLOB .

Once we have created the table, it's time to create id as autoincrement.

Just type this command, 

command

It will create a sequence, doc_id. Now, just see by selecting the statement if your sequence has been created or not .

command

Step 2 : Open Visual Studio

Open Visual Studio File->New Website.

New Website

Select ASP.NET Empty Website and Give suitable name as DocumentSaveInBinary,

DocumentSaveInBinary

Now, let's create FileUpload Control as,

code

  1. <asp:FileUpload ID="FileUpload1" runat="server" />  
  2.         <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" CssClass="btn-primary" />  
Now, create Gridview with Download Link button, so that we can download respective documents or Files .

code
  1. <asp:GridView ID="GridView1" runat="server"   
  2.               
  3.             AutoGenerateColumns="false" CssClass="table">  
  4.             <Columns>  
  5.                 <asp:BoundField DataField="Name" HeaderText="File Name" />  
  6.                 <asp:TemplateField ItemStyle-HorizontalAlign="Center">  
  7.                     <ItemTemplate>  
  8.                         <asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"  
  9.                             CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>  
  10.                     </ItemTemplate>  
  11.                 </asp:TemplateField>  
  12.             </Columns>  
  13.         </asp:GridView>  
Here you will see that inside Gridview used <asp:BoundField/> Showing HeaderText as FileName in gridview. In that <Itemtemplate></Itemtemplate> Inside Itemtemplate you need to bind Link button with ID=”lnkDownload” OnClick=”DownloadFile”.

So my final Document.aspx code is,
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="DocumentUpload.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head id="Head1" runat="server">  
  6.     <title></title>  
  7.     <link rel="Stylesheet" href="Styles/bootstrap.min.css" style="" />  
  8.         <link rel="Stylesheet" href="Styles/bootstrap.css" />  
  9. </head>  
  10. <body>  
  11.     <form id="form1" runat="server">  
  12.     <div class="container">  
  13.         <asp:FileUpload ID="FileUpload1" runat="server" />  
  14.         <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" CssClass="btn-primary" />  
  15.         <hr />  
  16.         <asp:GridView ID="GridView1" runat="server"   
  17.               
  18.             AutoGenerateColumns="false" CssClass="table">  
  19.             <Columns>  
  20.                 <asp:BoundField DataField="Name" HeaderText="File Name" />  
  21.                 <asp:TemplateField ItemStyle-HorizontalAlign="Center">  
  22.                     <ItemTemplate>  
  23.                         <asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"  
  24.                             CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>  
  25.                     </ItemTemplate>  
  26.                 </asp:TemplateField>  
  27.             </Columns>  
  28.         </asp:GridView>  
  29.     </div>  
  30.     </form>  
  31. </body>  
  32. </html>  
Step 3 : Now let's see CS Code Part

Our File Upload Code is :

code

As you see in the above code,  we are saving our table FileName,Contentype; here the content types are word, pdf, image and so on and then we are saving the posted file in binary format by using Stream. File which you had uploaded in Fileupload Control and is converted in the binary file through BinaryReader . 

Here, I have added a connection string in the code .

Now, while adding, you need to insert the id. See, what I had inserted:  sequencename.next val

When we were inserting in SQL, we were using “@” . Here, in Oracle, we are using “:”:
  1. string constr = "User ID=axis_nsdl;Password=a$xis_4321;Data Source=TSTDPSEC";  
  2.              using (OracleConnection con = new OracleConnection(constr))  
  3.              {  
  4.                  string query = "insert into tblFiles values (doc_id.nextval,:Name, :ContentType, :Data)";  
  5.                  using (OracleCommand cmd = new OracleCommand(query))  
  6.                  {  
  7.                      cmd.Connection = con;  
  8.                     // cmd.Parameters.AddWithValue(":id", Number);  
  9.                      cmd.Parameters.AddWithValue(":Name", filename);  
  10.                      cmd.Parameters.AddWithValue(":ContentType", contentType);  
  11.                      cmd.Parameters.AddWithValue(":Data", bytes);  
  12.                      con.Open();  
  13.                      cmd.ExecuteNonQuery();  
  14.                      con.Close();  
  15.                  }  
  16.              }  
  17.          }  
  18.      }  

 

  • Similarly, we will write the code for download, as we had created Onclick in gridview as Download File

    code

    Now, we Will Bind the gridView :

    code

    So my Final CS Code is
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Data;  
    6. using System.Data.SqlClient;  
    7. using System.IO;  
    8. using System.Web.UI.WebControls;  
    9. using System.Web;  
    10. using System.Configuration;  
    11. using System.Data.OracleClient;  
    12.   
    13. public partial class _Default : System.Web.UI.Page  
    14. {  
    15.   
    16.   
    17.   
    18.     private OracleConnection con = new OracleConnection("User ID=axis_nsdl;Password=a$xis_4321;Data Source=TSTDPSEC");  
    19.     protected void Page_Load(object sender, EventArgs e)  
    20.     {  
    21.         BindGrid();  
    22.     }  
    23.   
    24.     private void BindGrid()  
    25.     {  
    26.        //string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;  
    27.         string constr = "User ID=axis_nsdl;Password=a$xis_4321;Data Source=TSTDPSEC";  
    28.         using (OracleConnection con = new OracleConnection(constr))  
    29.         {  
    30.             using (OracleCommand cmd = new OracleCommand())  
    31.             {  
    32.                 cmd.CommandText = "select Id, Name from tblFiles";  
    33.                 cmd.Connection = con;  
    34.                 con.Open();  
    35.                 GridView1.DataSource = cmd.ExecuteReader();  
    36.                 GridView1.DataBind();  
    37.                 con.Close();  
    38.             }  
    39.         }  
    40.     }  
    41.     protected void Upload(object sender, EventArgs e)  
    42.     {  
    43.         string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);  
    44.         string contentType = FileUpload1.PostedFile.ContentType;  
    45.         using (Stream fs = FileUpload1.PostedFile.InputStream)  
    46.         {  
    47.             using (BinaryReader br = new BinaryReader(fs))  
    48.             {  
    49.                 byte[] bytes = br.ReadBytes((Int32)fs.Length);  
    50.                 string constr = "User ID=axis_nsdl;Password=a$xis_4321;Data Source=TSTDPSEC";  
    51.                 using (OracleConnection con = new OracleConnection(constr))  
    52.                 {  
    53.                     string query = "insert into tblFiles values (doc_id.nextval,:Name, :ContentType, :Data)";  
    54.                     using (OracleCommand cmd = new OracleCommand(query))  
    55.                     {  
    56.                         cmd.Connection = con;  
    57.                        // cmd.Parameters.AddWithValue(":id", Number);  
    58.                         cmd.Parameters.AddWithValue(":Name", filename);  
    59.                         cmd.Parameters.AddWithValue(":ContentType", contentType);  
    60.                         cmd.Parameters.AddWithValue(":Data", bytes);  
    61.                         con.Open();  
    62.                         cmd.ExecuteNonQuery();  
    63.                         con.Close();  
    64.                     }  
    65.                 }  
    66.             }  
    67.         }  
    68.         Response.Redirect(Request.Url.AbsoluteUri);  
    69.     }  
    70.   
    71.   
    72.   
    73.     protected void DownloadFile(object sender, EventArgs e)  
    74.     {  
    75.         int id = int.Parse((sender as LinkButton).CommandArgument);  
    76.         byte[] bytes;  
    77.         string fileName, contentType;  
    78.         string constr = "User ID=axis_nsdl;Password=a$xis_4321;Data Source=TSTDPSEC";  
    79.         using (OracleConnection con = new OracleConnection(constr))  
    80.         {  
    81.             using (OracleCommand cmd = new OracleCommand())  
    82.             {  
    83.                 cmd.CommandText = "select Name, Data, ContentType from tblFiles where Id=:Id";  
    84.                 cmd.Parameters.AddWithValue(":Id", id);  
    85.                 cmd.Connection = con;  
    86.                 con.Open();  
    87.                 using (OracleDataReader sdr = cmd.ExecuteReader())  
    88.                 {  
    89.                     sdr.Read();  
    90.   
    91.                     bytes = (byte[])sdr["Data"];  
    92.                     contentType = sdr["ContentType"].ToString();  
    93.                     fileName = sdr["Name"].ToString();  
    94.                 }  
    95.                 con.Close();  
    96.             }  
    97.         }  
    98.         Response.Clear();  
    99.         Response.Buffer = true;  
    100.         Response.Charset = "";  
    101.         Response.Cache.SetCacheability(HttpCacheability.NoCache);  
    102.         Response.ContentType = contentType;  
    103.         Response.AppendHeader("Content-Disposition""attachment; filename=" + fileName);  
    104.         Response.BinaryWrite(bytes);  
    105.         Response.Flush();  
    106.         Response.End();  
    107.     }  
    108.     
    109.     protected void BtnSearch_Click(object sender, System.EventArgs e)  
    110.     {  
    111.         
    112.           
    113.         con.Open();  
    114.         OracleCommand cmd = new OracleCommand("Select * from Name where tblFiles like '" + txtSearch.Text + "%'", con);  
    115.         OracleDataAdapter da = new OracleDataAdapter(cmd);  
    116.         DataSet ds = new DataSet();  
    117.         da.Fill(ds);  
    118.         con.Close();  
    119.         GridView1.DataSource = ds;  
    120.         GridView1.DataBind();  
    121.     }  
    122.     protected void btnBack_Click(object sender, System.EventArgs e)  
    123.     {  
    124.         Response.Redirect("index.html");  
    125.     }  
    126. }  
  • Just Run the Application Debug on Action Events to see the FileUpload and its content.

    Application


    application

    We have successfully uploaded the file. Now, let's download and see the data .

    data

    data

    We have successfully downloaded . Now, let's see the Oracle table part

    table part

    As you can see, the data is stored in BLOB format successfully.

Up Next
    Ebook Download
    View all
    Learn
    View all