項(xiàng)目中需要把存儲(chǔ)在數(shù)據(jù)庫Blob字段中字節(jié)流進(jìn)行以下相關(guān)的操作:
1.圖片文件直接在頁面中顯示;
2.Doc,PDF等文檔提示用戶下載。
這個(gè)需求需要解決2個(gè)問題,第一個(gè)問題,從數(shù)據(jù)庫中讀取Blob字段;第二個(gè)問題,根據(jù)文件的類型,圖片文件直接顯示,其他文件提供下載功能。
在這里讀取BLob字段的數(shù)據(jù)不是什么難點(diǎn),我們知道用Blob字段是保存的二進(jìn)制流文件,用Byte[]來保存即可。代碼如下:
- //獲得數(shù)據(jù)庫連接
- 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是讀出并需要返回的數(shù)據(jù),類型是byte[]
- data = new byte[input.available()];
- inStream.read(data);
- inStream.close();
- }
- inStream.close();
- con.commit();
- con.close();
對(duì)于如何按需求處理二進(jìn)制流文件,我的實(shí)現(xiàn)方式如下:
- 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");
- }
-
- /**
- * 對(duì)字節(jié)流進(jìn)行處理,圖片顯示,其他提供下載
- * @param fileName 文件名稱
- * @param bytes[] 文件二進(jìn)制流
- * @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();
- }
在前臺(tái)的JSP頁面中直接調(diào)用StreamOper方法即可。圖片和PDF二進(jìn)制流都可以在JSP中顯示,Doc,Excel等流直接提示用戶下載。
- <%
-
- FileDownloader.StreamOper(response, filename, pic, false);
-
- %>
這樣對(duì)于圖片,直接在JSP中顯示,對(duì)于其他問題提示用戶下載。
最后附上一段如何讀取文件轉(zhuǎn)換成二進(jìn)制流程代碼,供大家參考:
- ///讀取文件字節(jié)流
- 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;
- }
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。