参见:http://www.cnblogs.com/kakag/p/3145140.html
1、数据表:
create table tb_file(
-> fid SMALLINT AUTO_INCREMENT NOT NULL PRIMARY KEY,
-> fname VARCHAR(50) NOT NULL,
-> fcontent LONGBLOB NOT NULL );
注意:这里fcontent使用longblob类型;Blob是一个可以存储二进制文件的容器。刚开始我使用的是blob类型,但是在上传一张431.27kb的图片时,程序报错“data is too long”,后来Google到这里:
http://stackoverflow.com/questions/3503841/jpa-mysql-blob-returns-data-too-long
发现
TINYBLOB: maximum length of 255 bytes
BLOB: maximum length of 65,535 bytes(63.99kb)
MEDIUMBLOB: maximum length of 16,777,215 bytes(16383.99kb)
LONGBLOB: maximum length of 4,294,967,295 bytes(4194303.99kb)
所以当我使用blob时,最大容量只有64kb,所以在这里改为LONGBLOB类型
2、编写图片数据流存储的工具类:
public class ImageUtil {
private static File file=null;
public static FileInputStream getImageByte(String infile) throws FileNotFoundException{
FileInputStream imageByte=null;
file=new File(infile);
imageByte=new FileInputStream(file);
return imageByte;
}
}
3、将本地文件保存到数据库,在我的F:\eclipse\workspace\uploadpic\pic文件夹中有一张照片fanfan.jpg
public class UploadPic {
private static final String URL="jdbc:mysql://127.0.0.1:3306/uploadpic";
private static final String USER="root";
private static final String PASS="1234";
public static void main(String[] args) throws SQLException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager.getConnection(URL,USER,PASS);
InputStream in=ImageUtil.getImageByte("F://eclipse/workspace/uploadpic/pic/fanfan.jpg");
String sql="insert into tb_file(fname,fcontent) values(?,?)";
PreparedStatement ptmt=conn.prepareStatement(sql);
ptmt.setString(1,"凡凡");
ptmt.setBinaryStream(2, in,
in.available());
ptmt.execute();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
执行之后,在数据库中有:
没错,宝宝的凡凡哈哈!