Updating database Image just stores 0x. C#



I have a table that stores information of users, which is filled by loading a XML file. In that table, I have an Image type column that is for all users set as "null" in the XML file. The problem comes when I try to update that column and set an image, it just stores "0x".


This is the table:



create table User(
ID INTEGER PRIMARY KEY,
name VARCHAR(50),
foto IMAGE,
email VARCHAR(100))


This is my update code:



protected void addFoto_Click(object sender, EventArgs e)
{
Byte[] imgByte = null;
if (file_upload.PostedFile != null)
{
HttpPostedFile File = file_upload.PostedFile;
File.InputStream.Position = 0;
imgByte = new Byte[File.ContentLength];
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
string sql = "update User set foto = @foto where email= @email";
using(SqlCommand cmd = new SqlCommand(sql, con.getConexion()))
{
cmd.Parameters.AddWithValue("@email", Txtemail.Text.ToString());
cmd.Parameters.AddWithValue("@foto", imgByte);
con.open();
cmd.ExecuteNonQuery();
con.close();
}
}


I tried adding



File.InputStream.Position = 0;


as the answer in this post, but still didn't work.


Can't save byte[] array data to database in C#. It's saving 0x


I also tried with the column type VARBINARY(MAX) with this code:



string sql = "update User set foto = @foto where email= @email";
using (SqlCommand cmd = new SqlCommand(sql, con.getConexion()))
{
Stream fs = file_upload.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
cmd.Parameters.AddWithValue("@email", Txtemail.Text.ToString());
cmd.Parameters.Add("@foto", SqlDbType.Binary).Value = bytes;
con.open();
cmd.ExecuteNonQuery();
con.close();
}


Which just stored 0x000000... And finally, I also tried adding directly an image with:



System.Drawing.Image imag = System.Drawing.Image.FromStream(file_upload.PostedFile.InputStream);
cmd.Parameters.Add("foto", SqlDbType.Binary, 0).Value = ConvertImageToByteArray(imag, System.Drawing.Imaging.ImageFormat.Jpeg);


with no result.


If anyone can please tell me what I'm doing wrong I would be really grateful, and also excuse me if my english is not perfect.


No comments:

Post a Comment