使用java将文件(pdf、jpeg/fif)上载到mysql

vxqlmq5t  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(499)

这个问题在这里已经有答案了

使用java以二进制格式在数据库中存储图像(2个答案)
两年前关门了。
有没有办法在java中把文件附加到mysql上?我需要文件在数据库中,而不是路径中。

e0uiprwp

e0uiprwp1#

使用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;
}
balp4ylt

balp4ylt2#

这是如何编写二进制文件的示例代码,如pdf文档、ms excel电子表格、jpg/png图像文件或zip文件等。。到blob类型的数据库表列,并从数据库中读取。
我已经将它们分别用于JavaSE7或更高版本的ApacheDerby(又称JavaDB)和mysql数据库。
derby:write to 数据库:

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:write to 数据库:

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 )确保这些资源已关闭。

相关问题