寫此文章,是因為我之前也並沒有接觸過,上網找了許多資料,還是有七七八八的問題,最終解決了,做個記錄,免得之后忘記。
首先,先取出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;
}