using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
using System.Data.OleDb;
namespace uploadp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
}
private void Btx1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
String connectStr = "server=127.0.0.1;database=zbpt;user=rootzbpt;password=rotzbpt;port=3306;charset=utf8;SslMode = none";
MySqlConnection zbptconn = new MySqlConnection(connectStr);
zbptconn.Open();//打开通道,建立连接
if (Btp1.Image == null||Btx1.Text == "")
{
MessageBox.Show("照片或名称不能为空!!");
}
else
{
MySqlCommand mycmd = new MySqlCommand("insert into image(image,pu_name) values( ?image,'" + Btx1.Text + "')", zbptconn);
MySqlParameter param = new MySqlParameter();
param.MySqlDbType = MySqlDbType.VarBinary;
param.ParameterName = "?image";
param.Value = SaveImage(Btp1.Text);
mycmd.Parameters.Add(param);
if (mycmd.ExecuteNonQuery() > 0)
{
Console.WriteLine("success");
}
Console.ReadLine();
zbptconn.Close();//关闭
/* MessageBox.Show(SaveImage(Btp1.Text).ToString());*/
MessageBox.Show("图片上传成功!!!");
}
}
private void Btp1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
DialogResult result = open.ShowDialog();
Btp1.Text = open.FileName;
string path = this.Btp1.Text;
byte[] imgBytesIn = SaveImage(path);
if (result == DialogResult.OK)
{
Btp1.Image = Image.FromFile(open.FileName);
}
/*this.Btp1.Image = null;//不再显示图片*/
}
private void button1_Click_1(object sender, EventArgs e)
{
}
//将图片以二进制流
public byte[] SaveImage(String path)
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); //将图片以文件流的形式进行保存
byte[] imgBytesIn = new byte[fs.Length];
BinaryReader br = new BinaryReader(fs);
imgBytesIn = br.ReadBytes(Convert.ToInt32(fs.Length));
/*byte[] imgBytesIn = br.ReadBytes((int)fs.Length); //将流读入到字节数组中*/
return imgBytesIn;
}
//现实二进制流代表的图片
public void ShowImgByByte(byte[] imgBytesIn)
{
MemoryStream ms = new MemoryStream(imgBytesIn);
Btp1.Image = Image.FromStream(ms);
}
}
}