JdbcTemplate 操作Oracle Blob
写此文章,是因为我之前也并没有接触过,上网找了许多资料,还是有七七八八的问题,最终解决了,做个记录,免得之后忘记。
首先,先取出Blob字段,将其保存在字节数组中,之后用HTTP协议中下载文件的格式对应,主要只要写两个:
(1)response.setContentType("audio/wav");
(2)response.setHeader("Content-disposition","attachment;filename=" +URLEncoder.encode("report.wav", "utf-8"));
如果对Http协议不够熟悉,请查阅http://www.cnblogs.com/quanjia/archive/2010/11/01/1866753.html
由于我做的一个播放控件,需要的是文件的路径,所以我还将其写在一个文件中,代码都很详细。
1.DAO层
/**
* 获取汇报录音
*/
@Override
public void showReport(ComInput cip, ComOutput cop) {
String id=cip.get("id").toString();
sql.create();
sql.append(" SELECT T.audio FROM biaoming T ");
sql.append(" WHERE T.ID = ? ");
@SuppressWarnings("unchecked")
List blobBeans= jdbcTemplate.query(sql.toString(),new Object[]{id},
new org.springframework.jdbc.core.RowMapper() {
public Object mapRow(java.sql.ResultSet rs, int rowNum) throws SQLException {
byte[] iconByte = null;
java.sql.Blob blob = rs.getBlob(1);
if(blob != null){
java.io.InputStream inStream = blob.getBinaryStream();
iconByte = new byte[(int)blob.length()];
try {
inStream.read(iconByte);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return iconByte;
}
}
);
Action层:
ComOutput com = custReportService.showReport(cip);
if(com.getRetCode() == LbscConstant.SUCCESS){
byte[] recByte = (byte[])com.getRetObj();
if(recByte != null && recByte.length > 0){
response.setContentType("audio/wav");
try {
response.setHeader("Content-disposition",
"attachment;filename=" +
URLEncoder.encode("report.wav", "utf-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}try {
ServletOutputStream op = this.response.getOutputStream();
//保证文件名唯一,你可以用主键+时间啊等等方法
File file = new File("E:/JAVAspj/tomcat-7.0.69/webapps/report/test");
if(!file.exists()){
file.mkdirs();
}
// fileName表示你创建的文件名;
String fileName= id+".wav";
File f = new File(file,fileName);
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileOutputStream fout = new FileOutputStream(f);
op.write(recByte, 0, recByte.length);
fout.write(recByte);
op.close();
op = null;
fout.close();
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}