java - 使用java将文件(pdf,JPEG / FIF)上传到mysql
问题描述
有没有办法在java中将文件附加到mysql?我需要文件位于数据库而不是路径中。
解决方案
这是如何将二进制文件(如 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
)后,请确保这些资源已关闭。
推荐阅读
- c# - 开关盒没有变化
- php - 使用imagemagick显示pdf文件预览图片报错
- ios - iOS Swift VideoToolBox 解压帧 EXC_BAD_ADDRESS 错误
- kotlin - 如何使用核心库中提供的运算符递归生成 RxJava Flowable?
- javascript - 在 express js 服务器中使用节点应用程序
- python - 如何跳过一个标签并移动到下一个标签 - 使用 python 抓取网页
- html - HTML 可折叠按钮 - 如何将按钮突出显示为 href?
- apache-spark - 为什么 Spark RDD 为小数据保留更多数量的分区
- android - 如何将项目添加为依赖项?
- ios - 在 swift 5 中从另一个 tableview 控制器调用 tablview 控制器