Save Images And Data Files In Database Table In Binary Format

In this blog, we will learn, how to save the files in the database table. We will make a Web Application. It is a secure way to save the data files/images in the database in the table.

Let’s start.

Database part Work

  1. First, we create a table in SQL database.

    Eg:
    1. CREATE TABLE[dbo].[tbdata]  
    2. (  
    3.     [Blob][varbinary](maxNOT NULL, [Name][nvarchar](256) NULL, [Contenttype][nvarchar](256) NULLON[PRIMARY] TEXTIMAGE_ON[PRIMARY]  
    4. )  

Visual Studio

  1. Open Visual Studio. Select File >New > Web Site,

  2. Name it as you want. My application’s name is SampleWeb.

  3. First of all, Open Solution Explorer and right click on ( Website Name) > Add > Add New Item > select Web Form.

  4. Add file uploader, Label and button in Default.aspx page.

    Eg:
    1. <asp:FileUpload ID="FU1" runat="server" /> <br /> <br />  
    2. <asp:LinkButton ID="lb1" runat="server" Text="Submit" OnClick="lb1_Click" /> <br /><br />  
    3. <asp:Label id="Label1" runat="server" />  
  5. Add code on default.aspx.cs page,

    Eg:
    1. protected void lb1_Click(object sender, EventArgs e)   
    2. {  
    3.     if (FU1.HasFile) {  
    4.         try {  
    5.             string content_type = FU1.PostedFile.ContentType;  
    6.             string filename = FU1.PostedFile.FileName.ToLower();  
    7.             SqlConnection conn;  
    8.             SqlCommand cmd = new SqlCommand();  
    9.             conn = new SqlConnection("Data Source=DESKTOP-C4AN6J2\\SQLEXPRESS;Initial Catalog=test; Integrated Security=true;");  
    10.             conn.Open();  
    11.             BinaryReader br = new BinaryReader(FU1.PostedFile.InputStream);  
    12.             Byte[] bytes = br.ReadBytes((Int32) FU1.PostedFile.InputStream.Length);  
    13.             cmd.CommandText = "Insert into tbdata (Blob,Name,Contenttype)values( @bytes,@Name,@Contenttype)";  
    14.             cmd.Connection = conn;  
    15.             cmd.Parameters.AddWithValue("@bytes", bytes);  
    16.             cmd.Parameters.AddWithValue("@Name", filename);  
    17.             cmd.Parameters.AddWithValue("@Contenttype", content_type);  
    18.             cmd.ExecuteNonQuery();  
    19.             cmd.Dispose();  
    20.             cmd.Connection.Close();  
    21.             Label1.Text = "Uploaded Sucessfully";  
    22.         } catch {  
    23.             Label1.Text = "Not Uploaded Sucessfully";  
    24.         }  
    25.     } else Label1.Text = "No Upload";  
    26. }