在MSSQL中,圖片字段類型是IMAGE,但是在MYSQL中不存在IMAGE,而有的提到是用BOLB類型保存,我建議是用LONGBOLB,因?yàn)樵趫D片稍微較大時(shí),用BOLB保存的圖片只能顯示半節(jié)。下面是具體的代碼
上傳部分
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);這樣存在數(shù)據(jù)庫的大小會比圖片實(shí)際字節(jié)小,讀取的時(shí)候會顯示不了(呵呵,具體哪出錯了還沒來的急研究,但我在調(diào)試的時(shí)候就因?yàn)檫@樣郁悶了很久)
顯示代碼
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();
}