从数据库读取图片输出到页面中

来源:互联网 发布:php中美元符号 编辑:程序博客网 时间:2024/05/18 01:14

private void getAttachementByIDAndFieldName(Connection con ,String attachTableName, String attachId,
   String fieldName, HttpServletResponse resp) throws Exception {
   //PreparedStatement pstmt = con.prepareStatement("select attachblob,attachname,filesize,filetype from "+attachTableName+" where attachid = ? ");
   PreparedStatement pstmt = con.prepareStatement("select CONTENTS,FILE_NAME,FILE_SIZE,FILE_TYPE from "+attachTableName+" where FD_OBJECTID = ? ");
   pstmt.setString(1, attachId);
   ServletOutputStream out =null;
   InputStream is =null;
   try {
    ResultSet rs = pstmt.executeQuery();
    while(rs.next()){
     //设置头文件
//     resp.setContentType("application/force-download");
//     String disposition = "attachment;filename="+rs.getString(2);
//     resp.setHeader("Content-Disposition",new String(disposition.getBytes(),"ISO_8859_1"));
//     resp.setContentLength(rs.getInt(3));
     resp.setContentType("image/jpeg");
     resp.setContentLength(rs.getInt(3));
     out = resp.getOutputStream();
     oracle.sql.BLOB attachement =(oracle.sql.BLOB) rs.getBlob(1);
     is = attachement.getBinaryStream();
     byte[] byteBuffer = new byte[1024];
     while(is.read(byteBuffer)!=-1){
      out.write(byteBuffer ,0, byteBuffer.length);
     }
     is.close(); 
     out.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
    throw new Exception(e.getMessage());
   }finally{
    pstmt.close();
    try {
     if(is!=null){
      is.close(); 
     }
     if(out!=null){
      out.close();
     }
    } catch (IOException e) {
    }
   }
 }
  

页面:

<div><img id="pic"></img></div>
         <input id="viewPic" type="button" value="预览" onclick="viewPic()"/>

         function viewPic(){
          alert("view2");
          $("#pic")[0].src="attachmentdownload/attachmentIdentifyCardView?attachid=a779624b-0e2b-4f6c-bff2-c47caa0f1368=123&entityModelId=abc&fileName&cc.jpg&fieldName=phonto&attachId=c62a7452-41ee-4e3b-98f7-68cd5d5cd016&date="+new Date().getTime();
         }

原创粉丝点击