项目中需要把存储在数据库Blob字段中字节流进行以下相关的操作:
1.图片文件直接在页面中显示;
2.Doc,PDF等文档提示用户下载。
这个需求需要解决2个问题,第一个问题,从数据库中读取Blob字段;第二个问题,根据文件的类型,图片文件直接显示,其他文件提供下载功能。
在这里读取BLob字段的数据不是什么难点,我们知道用Blob字段是保存的二进制流文件,用Byte[]来保存即可。代码如下:
//获得数据库连接
Connection con = ConnectionFactory.getConnection();
con.setAutoCommit(false);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select BLOBATTR from TESTBLOB where ID=1");
if (rs.next())
{
java.sql.Blob blob = rs.getBlob("BLOBATTR");
InputStream inStream = blob.getBinaryStream();
//data是读出并需要返回的数据,类型是byte[]
data = new byte[input.available()];
inStream.read(data);
inStream.close();
}
inStream.close();
con.commit();
con.close();
对于如何按需求处理二进制流文件,我的实现方式如下:
static {
MIME = new Hashtable();
MIME.put("jpeg", "image/jpeg");
MIME.put("jpg", "image/jpeg");
MIME.put("jfif", "image/jpeg");
MIME.put("jfif-tbnl", "image/jpeg");
MIME.put("jpe", "image/jpeg");
MIME.put("jfif", "image/jpeg");
MIME.put("tiff", "image/tiff");
MIME.put("tif", "image/tiff");
MIME.put("gif", "image/gif");
MIME.put("xls", "application/x-msexcel");
MIME.put("doc", "application/msword");
MIME.put("ppt", "application/x-mspowerpoint");
MIME.put("zip", "application/x-zip-compressed");
MIME.put("pdf", "application/pdf");
}
/**
* 对字节流进行处理,图片显示,其他提供下载
* @param fileName 文件名称
* @param bytes[] 文件二进制流
* @param down 是否下载
*
* @return
*/
public static void StreamOper(HttpServletResponse response, String fileName, byte bytes[], boolean down)
throws IOException {
int index = 0;
String ext = "";
if ((index = fileName.indexOf('.')) > 0)
ext = fileName.substring(index + 1);
//通过文件名的后缀判断文件的格式
String mime = (String) MIME.get(ext);
if (mime == null)
mime = "application/x-msdownload";
response.setContentType(mime);
//是否需要提供下载
if (down)
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
OutputStream outStream = response.getOutputStream();
outStream.write(bytes, 0, bytes.length);
outStream.flush();
outStream.close();
}
在前台的JSP页面中直接调用StreamOper方法即可。图片和PDF二进制流都可以在JSP中显示,Doc,Excel等流直接提示用户下载。
<%
FileDownloader.StreamOper(response, filename, pic, false);
%>
这样对于图片,直接在JSP中显示,对于其他问题提示用户下载。
最后附上一段如何读取文件转换成二进制流程代码,供大家参考:
///读取文件字节流
public static byte[] readerFileStream(String fileName)
throws IOException {
File f = new File(fileName);
int length = (int)f.length();
byte[] buff = new byte[length];
BufferedInputStream bis = null;
bis = new BufferedInputStream(new FileInputStream(fileName));
int bytesRead;
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
}
return buff;
}