在MSSQL中,图片字段类型是IMAGE,但是在MYSQL中不存在IMAGE,而有的提到是用BOLB类型保存,我建议是用LONGBOLB,因为在图片稍微较大时,用BOLB保存的图片只能显示半节。下面是具体的代码
上传部分
int len = FileUpload1.PostedFile.ContentLength;
byte[] pic = new byte[len];
FileUpload1.PostedFile.InputStream.Read(pic, 0, len);
string strImageType = FileUpload1.PostedFile.ContentType;
MySqlConnection connection = DAL.DBHelp.Conn();
// SqlConnection connection = new
//SqlConnection(@"server=ALLEN\SQLEXPRESS;Initial Catalog=GibbsCAMCert;Integrated Security=True");
try
{
// connection.Open();
// SqlCommand cmd = new SqlCommand("insert into photo "
/// + "(photo, type) values (@pic, @text)", connection);
string sql = "update tbl_resume set c_photo=?c_photo where c_uid='aaa111'";//, connection
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connection;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("?c_photo", pic);//.Paramters.AddWithValue();
string ss = cmd.CommandText;
cmd.ExecuteNonQuery();
//cmd.Parameters.Add("@pic", pic);
//cmd.Parameters.Add("@text", strImageType);
//cmd.ExecuteNonQuery();
}
finally
{
connection.Close();
}
注:如果是测试直接用
MySqlCommand cmd = new MySqlCommand("update tbl_resume set c_photo='"+pic+"' where c_uid='aaa111'",connection);这样存在数据库的大小会比图片实际字节小,读取的时候会显示不了(呵呵,具体哪出错了还没来的急研究,但我在调试的时候就因为这样郁闷了很久)
显示代码
MemoryStream stream = new MemoryStream();
// SqlConnection connection = new SqlConnection(@"server=ALLEN\SQLEXPRESS;Initial Catalog=GibbsCAMCert;Integrated Security=True");
MySqlConnection connection = DAL.DBHelp.Conn();
try
{
//connection.Open();
// SqlCommand command = new SqlCommand("select photo from photo", connection);
MySqlCommand command = new MySqlCommand("select c_photo from tbl_resume where c_uid='aaa111'", connection);
byte[] image = (byte[])command.ExecuteScalar();
stream.Write(image, 0, image.Length);
Bitmap bitmap = new Bitmap(stream);
Response.ContentType = "image/gif";
bitmap.Save(Response.OutputStream, ImageFormat.Gif);
}
finally
{
connection.Close();
stream.Close();
}