Oracle库blob的文件上传和下载

作为园龄最小的博主  请大家多多关照 ,这是本人的第一篇博客 ,希望对大家有所帮助 话不多说,直接上精华--------

/**
* 报告上传
*
* @throws Exception
*/
@Action
public void test() throws Exception {
HttpServletResponse response = ActionContext.getActionContext().getHttpServletResponse();

//本地测试文件
FileInputStream read = new FileInputStream("C:\\Users\\93114\\Desktop\\123.doc");
final File f = new File("C:\\Users\\93114\\Desktop\\123.doc");
StringBuilder sql = new StringBuilder();

//数据库中需要添加内容的blob字段

sql.append("update XY28 set XY2805=?");
final LobHandler lobHandler = new DefaultLobHandler(); //定义一个lob的操作类
this.jdbcTemplate.execute(sql.toString(), new AbstractLobCreatingPreparedStatementCallback(lobHandler) {
@Override
protected void setValues(PreparedStatement pstm, LobCreator lobCreator) throws SQLException, DataAccessException {
lobCreator.setBlobAsBinaryStream(pstm, 1, read, (int) f.length());
}
});
read.close();
}


/**
* 报告文件下载
*/
@Action
public void download() {
HttpServletRequest request = ActionContext.getActionContext().getHttpServletRequest();
HttpServletResponse response = ActionContext.getActionContext().getHttpServletResponse();
String id = request.getParameter("id");//获取需要下载的文件recordid
try {
ServletOutputStream out = response.getOutputStream();
StringBuilder sql = new StringBuilder();
StringBuilder filename = new StringBuilder();//查询文件
sql.append("select XY2805 from XY28 where recordid=? ");

//为下载的文件命名
filename.append("select XY2803 from XY28 where recordid=? ");
Map<String, Object> map = this.jdbcTemplate.queryForMap(filename.toString(), id);
String file_name = map.get("XY2803").toString();
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(file_name + ".doc", "UTF-8"));
final LobHandler lobHandler = new DefaultLobHandler(); //定义一个lob的操作类
final StringBuilder xy3105 = new StringBuilder();

this.jdbcTemplate.query(sql.toString(), new AbstractLobStreamingResultSetExtractor<Object>() {
@Override
protected void streamData(ResultSet rs) throws SQLException, IOException, DataAccessException {
InputStream is = lobHandler.getBlobAsBinaryStream(rs, "XY2805");
FileCopyUtils.copy(is, out);
is.close();
}
}, id);
out.flush();
out.close();
} catch (Exception e) {
logger.info("下载信用报告异常");
}
}

文章简单明了  代码直接可以使用  求关注!!!!!!

posted @ 2019-09-17 15:05  奔跑的蜗牛`  阅读(646)  评论(0编辑  收藏  举报