将图像转换为二进制以存储在 asp.net 中的数据库中

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

我想使用 varbinary(MAX).

将图像(任何类型的图像)存储到数据库中

我的数据库:

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

我的代码:

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();
}

当我 运行 我的代码时,我得到这个错误:

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

我该如何解决这个问题?

始终使用参数化 sql 查询来检索数据,同时也存储数据。这将防止 SQL 注入攻击的发生,并使您能够在数据库中存储(大)二进制对象。

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();
}

这是供您查看的资源。我认为 this 可以解决您的问题。

请注意:在代码中对数据库进行操作时使用存储过程。