Save Images And Files In Database

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. [Blob] [varbinary](maxNOT NULL,  
    3. [Name] [nvarchar](256) NULL,  
    4. [Contenttype] [nvarchar](256) NULL  
    5. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  

Visual Studio

  1. Open Visual Studio, select File >New > Website

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

    SampleWeb

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

    Select Web Form

  4. Add the 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" />  
    code

  5. Add the code on Default.aspx.cs page:

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