JSP頁面顯示和下載字節流文件

先隨便粘一下,有空整理下……

項目中需要把存儲在數據庫Blob字段中字節流進行以下相關的操作:

  1.圖片文件直接在頁面中顯示;

  2.Doc,PDF等文檔提示用戶下載。

  這個需求需要解決2個問題,第一個問題,從數據庫中讀取Blob字段;第二個問題,根據文件的類型,圖片文件直接顯示,其他文件提供下載功能。

  在這裏讀取BLob字段的數據不是什麼難點,我們知道用Blob字段是保存的二進制流文件,用Byte[]來保存即可。代碼如下:

以下是代碼片段:
  view plain//獲得數據庫連接 
  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(); 
  對於如何按需求處理二進制流文件,我的實現方式如下: view plainstatic { 
  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"); 
  } 
  /** 
  * 對字節流進行處理,圖片顯示,其他提供下載 
  * @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"; 
  //是否需要提供下載 
  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方法即可。

  view plain<%

  FileDownloader.StreamOper(response, filename, pic, false);

  %>

  這樣對於圖片,直接在JSP中顯示,對於其他問題提示用戶下載。

  最後附上一段如何讀取文件轉換成二進制流程代碼,供大家參考:

  

以下是代碼片段:
view plain///讀取文件字節流 
  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; 
  }
轉自:JSP頁面顯示和下載字節流文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章