上一篇说了Blob字段的入库
这次说一下Blob字段的出库,也就是读取Blob字段中存的数据,因为不知道Blob字段中存的数据(文件)时什么类型的,所以可以在存入数据库的时候,每一条数据对应的存上Blob中存入的文件的文件名(一定带上文件格式),下面的代码都是在这个条件下完成的,如果你的Blob字段不知道存的什么类型的文件,那么…
首先要拿到你要获取的Blob所在的那条数据,就是一条查询语句,然后接收查询结果嘛,这就不用写了吧,我就略过了,不同的框架不同的写法,但是结果都是拿到一条含有Blob的数据:
Test t = new Test();//new一个对象用来接收查询的数据
// 初始化驱动包
Class.forName("oracle.jdbc.driver.OracleDriver");
// 根据数据库连接字符,名称,密码给conn赋值
conn = DriverManager.getConnection("url", "user", "password");
String sql = "select filename,blobvalue from test where id = '123456'";//假设这是拿到blob的sql
st = (Statement) conn.createStatement(); // 创建用于执行静态sql语句的Statement对象
rs = st.executeQuery(sql); // 执行查询的sql语句
while (rs.next()) {
t.setFileName(rs.getString("filename"));//获取Blob字段存储的文件名和格式
t.setBlobValue(rs.getBlob("blobvalue"));//获取Blob字段的数据
}
String fileName = t.getFileName();//单独拿出来文件名,方便用
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
OutputStream fos = null;
InputStream fis = null;
try{
Blob blob = t.getBlobValue();
fis = blob.getBinaryStream();
bis = new BufferedInputStream(fis);
fos = response.getOutputStream();
bos = new BufferedOutputStream(fos);
setFileDownloadHeader(request,response, fileName);//这个单独写一个方法,这个是防止下载的文件名乱码用的
int byteRead = 0;
byte[] buffer = new byte[8192];
while((byteRead=bis.read(buffer,0,8192))!=-1){
bos.write(buffer,0,byteRead);
}
bos.flush();
fis.close();
bis.close();
fos.close();
bos.close();
}catch(IOException e){
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}finally{
fos.close();
fis.close();
}
public static void setFileDownloadHeader(HttpServletRequest request,HttpServletResponse response, String fileName) {
try {
//中文文件名支持
String encodedfileName = null;
String agent = request.getHeader("USER-AGENT");
if(null != agent && -1 != agent.indexOf("MSIE")){//IE
encodedfileName = java.net.URLEncoder.encode(fileName,"UTF-8");
}else if(null != agent && -1 != agent.indexOf("Mozilla")){
encodedfileName = new String (fileName.getBytes("GBK"),"iso-8859-1");
}else{
encodedfileName = java.net.URLEncoder.encode(fileName,"UTF-8");
}
//下面提供两种写法,根据不同情况选择使用,一般下载使用第一种
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");//点击会提供对话框选择另存为
//response.setHeader( “Content-Disposition “, “inline;filename= “+fliename)//通过IE浏览器直接选择相关应用程序插件打开
//
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
好了,上面的代码就可以实现Blob字段的出库,效果就是点击下载,浏览器会弹出下载框, 出库比较简单,没有入库那么麻烦,文章纯手打,有错误的地方请谅解。
原创:影公子 ——转载请注明原帖链接