Can a varbinary type be used to store an image in a SQL Server database?

I am trying to save an image in my SQL Server database, what data type should I use?

In below code aspx.csI am trying to read all the bytes from the input stream of the request and store it in the database, but the array is byte[]not updated properly in the table. Did I miss something?

protected void Page_Load(object sender, EventArgs e)
{
        Request.InputStream.Position = 0;

        byte[] Contents = new byte[Request.InputStream.Length];

        Request.InputStream.Read(Contents, 0, (int)Request.InputStream.Length);

        con.Open();

        try
        {
            string query = "update tblImageUpload set " + IMAGE_ID + " = @imageBytes where Image_ID='" + CID + "'";

            int i = 0;

            using (cmd = new SqlCommand(query, con))
            {
                cmd.Parameters.Add("@imageBytes", SqlDbType.VarBinary, Contents.Length).Value = Contents;

                 i = cmd.ExecuteNonQuery();
            }

            Response.Write("Upload Query = " + query);
            Response.Write("Upload Code = " + i);
        } catch (Exception ex) {
            Response.Write("Upload Code=" + ex);
        }
+5
source share
1 answer

You can use VARBINARYyes. You are probably best off with VARBINARY(MAX)to save them.

You can use it as follows:

cmd.Parameters.Add("@imageBytes", SqlDbType.VarBinaryMax);
cmd.Parameters["@imageBytes"].Value = Contents;
+7
source

All Articles