不多说了,直接上代码
//读取上传
private void btnup_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "选择要上传的图片";
ofd.Filter = "All Files(*.*)|*.*|位图(*.bmp)|*.bmp|JPEG(*.jpg)|*.jpg";
ofd.ShowDialog();
textBox1.Text = ofd.FileName;
if (!File.Exists(ofd.FileName))
{
MessageBox.Show("照片为空");
return;
}
}
private void btnupload_Click(object sender, EventArgs e)
{
if (txtName.Text == "")
{
MessageBox.Show("照片描述为空");
return;
}
string strPath = textBox1.Text.Trim();
string Name = txtName.Text.ToString();
FileStream fs = new FileStream(strPath, FileMode.Open, FileAccess.Read);
byte[] byteFile = new byte[fs.Length];
fs.Read(byteFile, 0, (int)fs.Length);
fs.Close();
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True");
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
string strSql = "insert into testImg(FileName,Img,ImgName) Values(@FileName,@Img,@ImgName)";
cmd.CommandText = strSql;
SqlParameter[] parameters = new SqlParameter[3];
parameters[0] = new SqlParameter("@FileName", SqlDbType.NVarChar, 200);
parameters[0].Value = strPath;
parameters[1] = new SqlParameter("@Img", SqlDbType.Image, int.MaxValue);
parameters[1].Value = byteFile;
parameters[2] = new SqlParameter("@ImgName", SqlDbType.NVarChar, 200);
parameters[2].Value = Name;
cmd.Parameters.AddRange(parameters);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("上传成功");
Bind();
}
catch
{
conn.Close();
MessageBox.Show("上传失败!");
}
}
//显示
private void btnDownLoad_Click(object sender, EventArgs e)
{
byte[] bytFile;
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True");
try
{
SqlCommand cmd = new SqlCommand();
string strSql = "select img from testImg where id='" + comboBox1.SelectedValue.ToString() + "'";
cmd.Connection = conn;
cmd.CommandText = strSql;
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
bytFile = (Byte[])sdr["Img"];
}
else
{
bytFile = new byte[0];
}
sdr.Close();
conn.Close();
MemoryStream ms = new MemoryStream(bytFile, 0, bytFile.Length);
this.picImage.Image = Image.FromStream(ms);
ms.Close();
}
catch
{
conn.Close();
MessageBox.Show("失败");
}
}
//刷新初始化
void Bind()
{
string sql = "select * from testimg";
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter sqldaper = new SqlDataAdapter(cmd);
sqldaper.Fill(ds);
con.Close();
comboBox1.DataSource = ds.Tables[0];
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "ImgName";
}