首先在数据库中用mediumblob来保存图片的位置
Mysql中可以存储大文件数据,一般使用的BLOB对象。如图片,视频等等。
BLOB是一个二进制大对象,可以容纳可变数量的数据。因为是二进制对象,所以与编码方式无关。有4种BLOB类型:TINYBLOB、BLOB、MEDIUMBLOB和LONGBLOB。它们只是可容纳值的最大长度不同。
四种字段类型保存的最大长度如下:
TINYBLOB - 255 bytes
BLOB - 65535 bytes(64KB)
MEDIUMBLOB - 16,777,215 bytes(16MB) (2^24 - 1)
LONGBLOB - 4G bytes (2^32 – 1)
CREATE TABLE p (
id int,
photo mediumblob
);
随后进行链接数据库 将图片的路径读取到后 转化成二进制流文件后 进行上传
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e){
e.printStackTrace();
}
Connection conn = null;
String jdbcPath = "jdbc:mysql://localhost:3306/photos";
String user = "root";
String pass = "";
PreparedStatement ps = null;
ResultSet rs = null;
InputStream in = null;
try {
conn = DriverManager.getConnection(jdbcPath,user,pass);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//从本地硬盘硬盘读取一张图片保存到数据库
in =new FileInputStream("D:/img1.jpg");
ps=conn.prepareStatement("insert into photos.p values(?,?)");
ps.setInt(1,2);
ps.setBinaryStream(2, in, in.available());
ps.executeUpdate();
in.close();
}catch(SQLException e){
}
进行上传即可 将图片进行读出 需要指定图片读出后的位置和和将图片读出后制定的路径
ps=con.prepareStatement("select * from test.phototest where id=?");
24 ps.setInt(1,2);
25 rs=ps.executeQuery();
26 rs.next(); //将光标指向第一行
27 in=rs.getBinaryStream("photo");
28 byte[] b=new byte[in.available()]; //新建保存图片数据的byte数组
29 in.read(b);
30 OutputStream out=new FileOutputStream("222.jpg");
31 out.write(b);
32 out.flush();
33 out.close();
这样即可