Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Save image to database using asp.net

Suggested Videos
Part 166 - Captcha control in asp.net
Part 167 - Using ASP.NET validation controls with recaptcha
Part 168 - Customizing recaptcha control



In this video we will discuss how to save images to database table using asp.net and c#.



Save image to database using asp.net

When upload button is clicked, the image should be uploaded to a database table and "View Uploaded Image" link should appear. When you click on this link we should load the image from the database and display it on the web page.

upload image to database asp.net

In this video we will discuss how to upload the image to the database. In our next video we will discuss how to download the image from the database and display it on the web page.

Step 1 : Create table tblImages. This table stores the uploaded images along with it's name and size in bytes.

Create table tblImages
(
    Id int primary key identity,
    Name nvarchar(255),
    Size int,
    ImageData varbinary(max)
)
Go

Step 2 : Create stored procedure to insert image data 

Create procedure spUploadImage
@Name nvarchar(255),
@Size int,
@ImageData varbinary(max),
@NewId int output
as
Begin
    Insert into tblImages
    values (@Name, @Size, @ImageData)

    Select @NewId = SCOPE_IDENTITY()
End
Go

Step 3 : Create new asp.net web application project. Name it Demo. 

Step 4 : Include a connection string in the web.config file to your database.
<add name="DBCS"
  connectionString="server=.;database=SampleDB;integrated security=SSPI"/>

Step 5 : Add 2 WebForms to the ASP.NET project. Name them WebForm1.aspx and WebForm2.aspx.

Step 6 : Copy and paste the following HTML on WebForm1.aspx

<asp:FileUpload ID="FileUpload1" runat="server" />
<br /><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
<br /><br />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
<br /><br />
<asp:HyperLink ID="hyperlink" runat="server">View Uploaded Image</asp:HyperLink>

Step 7 : Copy and paste the following code in WebForm1.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web;

namespace Demo
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                lblMessage.Visible = false;
                hyperlink.Visible = false;
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            HttpPostedFile postedFile = FileUpload1.PostedFile;
            string filename = Path.GetFileName(postedFile.FileName);
            string fileExtension = Path.GetExtension(filename);
            int fileSize = postedFile.ContentLength;

            if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".gif"
                || fileExtension.ToLower() == ".png" || fileExtension.ToLower() == ".bmp")
            {
                Stream stream = postedFile.InputStream;
                BinaryReader binaryReader = new BinaryReader(stream);
                Byte[] bytes = binaryReader.ReadBytes((int)stream.Length);


                string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                using (SqlConnection con = new SqlConnection(cs))
                {
                    SqlCommand cmd = new SqlCommand("spUploadImage", con);
                    cmd.CommandType = CommandType.StoredProcedure;

                    SqlParameter paramName = new SqlParameter()
                    {
                        ParameterName = @"Name",
                        Value = filename
                    };
                    cmd.Parameters.Add(paramName);

                    SqlParameter paramSize = new SqlParameter()
                    {
                        ParameterName = "@Size",
                        Value = fileSize
                    };
                    cmd.Parameters.Add(paramSize);

                    SqlParameter paramImageData = new SqlParameter()
                    {
                        ParameterName = "@ImageData",
                        Value = bytes
                    };
                    cmd.Parameters.Add(paramImageData);

                    SqlParameter paramNewId = new SqlParameter()
                    {
                        ParameterName = "@NewId",
                        Value = -1,
                        Direction = ParameterDirection.Output
                    };
                    cmd.Parameters.Add(paramNewId);

                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();

                    lblMessage.Visible = true;
                    lblMessage.ForeColor = System.Drawing.Color.Green;
                    lblMessage.Text = "Upload Successful";
                    hyperlink.Visible = true;
                    hyperlink.NavigateUrl = "~/WebForm2.aspx?Id=" +
                        cmd.Parameters["@NewId"].Value.ToString();
                }
            }
            else
            {
                lblMessage.Visible = true;
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "Only images (.jpg, .png, .gif and .bmp) can be uploaded";
                hyperlink.Visible = false;
            }
        }
    }
}

In our next video we will discuss how to download an image from the database and display it on the web page.

6 comments:

  1. sir,
    How to convert any format image to jpeg and set resolution in c#.

    ReplyDelete
  2. Dear sir i have this problem can you pls help me

    I have a pblm in image uploading that it is showing an error that "Error converting data type nvarchar to int" and showing on cmd.executenonquery();

    ReplyDelete
  3. how to do
    this in asp.net core 2 mvc

    ReplyDelete
  4. if i use asp:updatepanel no posted file is coming thowrn exception null refreence

    ReplyDelete

It would be great if you can help share these free resources