首页 > 解决方案 > 使用java将文件(pdf,JPEG / FIF)上传到mysql

问题描述

有没有办法在java中将文件附加到mysql?我需要文件位于数据库而不是路径中。

标签: javamysqlfile-uploadblobbinary-data

解决方案


这是如何将二进制文件(如 PDF 文档、MS Excel 电子表格、JPG/PNG 图像文件或 ZIP 文件等)写入 BLOB 类型的数据库表列并从数据库中读取的示例代码.

我已经将这些与 Java SE 7 或更高版本分别与 Apache Derby(又名 Java DB)和 MySQL 数据库一起使用。

德比: 写入数据库:

Path path = Paths.get("MyPic.jpg");
InputStream instream = Files.newInputStream(path);
PreparedStatement pstmnt = getConnection().prepareStatement(dml); // dml is an sql Insert   
pstmnt.setBinaryStream(1, instream);
// pstmnt.setNull(1, Types.BLOB); // to set null value in db
pstmnt.executeUpdate();
pstmnt.close();
instream.close();

从数据库读取:

PreparedStatement pstmnt = getConnection().prepareStatement(sql); // sql is a Select
ResultSet rs = pstmnt.executeQuery();
rs.next();
InputStream instream = rs.getBinaryStream("col_name");
Path path = Paths.get("MyPic.jpg");
OutputStream outstream = Files.newOutputStream(path);
int len = 0;
byte [] buf = new byte [1024];
while ((len = instream.read(buf)) > 0) {
    outstream.write(buf, 0, len);
}
instream.close();
outstream.flush();
outstream.close();      
pstmnt.close();


MySQL: 写入数据库:

PreparedStatement pstmnt_= conn.prepareStatement(DML) // sql Insert
InputStream instream = Files.newInputStream(filePath); // filePath is of type Path
pstmnt.setBinaryStream(1, instream);
pstmnt.executeUpdate();
// close resources here

从数据库读取:

PreparedStatement pstmnt = conn.prepareStatement(DML); // sql Select
ResultSet rs = pstmnt.executeQuery();
rs.next();
Blob blob = rs.getBlob("col_name");
long len = blob.length();
byte [] fileBytes = blob.getBytes(1L, (int) len); // start pos = 1L
OutputStream out = ...
out.write(fileBytes);
out.flush();
out.close();

请注意,在使用 JDBC 对象(例如,PreparedStatement)和文件 io 流(例如,InputStream)后,请确保这些资源已关闭。


推荐阅读