Maple
Maple

Reputation: 179

Convert image to binary to store in database in asp.net

I want to store the image(any type of image) into the database by using varbinary(MAX).

My Database:

CREATE TABLE [dbo].[Pic]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY, 
    [picture] VARBINARY(MAX) NULL, 
    [origin] NVARCHAR(100) NULL
)

My code:

protected void Button1_Click(object sender, EventArgs e)
{
    byte[] imagebyte = File.ReadAllBytes(Server.MapPath("~/") + imageUpload1);

    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "insert into Pic values('"+ imagebyte +"','"+ lblOrigin.Text +"')";
    cmd.ExecuteNonQuery();
}

when I run my code, I get this error:

Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. at cmd.ExecuteNonQuery();

How can I solve this problem?

Upvotes: 0

Views: 1534

Answers (2)

Hounddog75
Hounddog75

Reputation: 75

Here is a resource for you to look at. I think this will solve your problem.

Just a note: Use stored procedures when doing operations on a database in your code.

Upvotes: 0

GvS
GvS

Reputation: 52511

Always use parameterized sql queries, to retrieve data, but also to store data. This will prevent SQL injection attacks from happening, and will enable you to store (large) binary objects in your database.

using (SqlCommand cmd = con.CreateCommand()) {
  cmd.CommandType = CommandType.Text;
  cmd.CommandText = "insert into Pic (picture, origin) values(@image, @origin)";

  // cmd.Parameters.AddWithValue("@image", imagebyte);
  cmd.Parameters.Add("@image", SqlDbType.VarBinary);
  cmd.Parameters["@image"].Value = imagebyte;

  cmd.Parameters.AddWithValue("@origin", lblOrigin.Text);
  cmd.ExecuteNonQuery();
}

Upvotes: 2

Related Questions