首先实现文件存储需要字段设置为blob类型
文件存储如下:
Connection conn = db.getConnection();
String sql = "insert into user1.table1(id, filename, document) VALUES(?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, Integer.parseInt(id));
ps.setString(2, fileName);
InputStream fileContent = fileItem.getInputStream();
ps.setBinaryStream(3, fileContent, fileContent.available());
ps.executeUpdate();
这里cjtbp.Tzthydhsqfjb中document字段为blob类型。
ps.setBinaryStream(3, fileContent, fileContent.available());中第二个参数为输入流,第三个参数为数据长度。
文件读取如下:
Connection conn = db.getConnection();
String sql = "select t.id, t.zthydhsqid, t.filename, t.document from user1.table1 t where t.id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, ZTHYDHSQFJID);
ResultSet rs = ps.executeQuery();
if(rs.next()){
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob("DOCUMENT");
InputStream fileContent = blob.getBinaryStream();
OutputStream os = response.getOutputStream();
int len = 0;
byte[] b = new byte[1024];
while ((len = fileContent.read(b)) > 0) {
os.write(b, 0, len);
}
fileContent.close();
os.close();
}
获取blob类型字段的内容时需要调用getBlob()方法,获取到Blob对象后然后获取其输入流,就可以了