【发布时间】:2019-01-07 05:50:13
【问题描述】:
有没有办法在java中将文件附加到mysql?我需要文件在数据库中而不是路径中。
【问题讨论】:
-
你能提供更多的上下文吗?到目前为止,您尝试过什么,您在为什么而苦苦挣扎?
标签: java mysql file-upload blob binary-data
有没有办法在java中将文件附加到mysql?我需要文件在数据库中而不是路径中。
【问题讨论】:
标签: java mysql file-upload blob binary-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)后,请确保这些资源已关闭。
【讨论】:
使用base64编码并保存为BLOB数据
这是一个编码示例:
/**
* Method used for encode the file to base64 binary format
* @param file
* @return encoded file format
*/
private String encodeFileToBase64Binary(File file){
String encodedfile = null;
try {
FileInputStream fileInputStreamReader = new FileInputStream(file);
byte[] bytes = new byte[(int)file.length()];
fileInputStreamReader.read(bytes);
encodedfile = Base64.encodeBase64(bytes).toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encodedfile;
}
【讨论】: