记得当年当当网推出时用JSP读取数据库是从Oracle里读Blob图片,显示到页面上以后怎么都是个红叉子,无奈之下请教高人,答曰:这种事情一般用Servlet搞定比较好,因为JSP读取数据库终究会被翻译成JAVA代码然后编译成class,你的JSP难免出现一些格式转换什么的代码,一旦污染到读出来的image,则红叉子在所难免了。
细想之下顿觉言之有理,Google之。果然发现很多朋友遇到过此问题,遂查之~,见有人说去掉全部空格就OK了,想想也对,就马上给代码净身(可怜我里缩外进的完美代码格式)~~
然后代码成了这副模样:
Java代码
- <%@ page import="java.awt.image.BufferedImage"%>
- <%@ page import="java.io.BufferedInputStream"%>
- <%@ page import="java.io.IOException"%>
- <%@ page import="java.sql.Connection"%>
- <%@ page import="java.sql.ResultSet"%>
- <%@ page import="java.sql.Statement"%>
- <%@ page import="java.sql.Blob"%>
- <%@ page import="oracle.sql.BLOB"%>
- <%@ page import="javax.naming.InitialContext"%>
- <%@ page import="javax.imageio.ImageIO"%>
- <%@ page import="javax.sql.DataSource"%>
- <%@ page import="javax.servlet.ServletOutputStream"%>
- <%@ page import="com.sun.image.codec.jpeg.JPEGCodec"%>
- <%@ page import="com.sun.image.codec.jpeg.JPEGImageEncoder"%>
- <%InitialContext ic=new InitialContext();
- DataSource ds=(DataSource)ic.lookup("DSNAME");
- Connection conn=null;
- conn =ds.getConnection);
- Statement stmt=null;BufferedInputStream inputimage=null;
- stmt=conn.createStatement();
- boolean defaultCommit=conn.getAutoCommit();
- conn.setAutoCommit(false);
- String photoId =request.getParameter("photo_id");
- try{
- ResultSet rs=stmt.executeQuery("SELECT * FROM TABLENAME WHERE sys_id='"+photoId+"'");
- if(rs.next()){Blob blob=(Blob)rs.getBlob("photo");
- long size=blob.length();
- byte[] bs=blob.getBytes(1,(int)size);
- response.setContentType("image/jpeg;charset=GB2312");
- response.setHeader("Content-Transfer-Encoding","base64");
- OutputStream out1=response.getOutputStream();
- BufferedOutputStream bos=null;
- bos=new BufferedOutputStream(out1);
- bos.write(bs,0,bs.length);bos.close();
- rs.close();
- }
- else
- {
- rs.close();
- }}
- finally{
- conn.close();
- }%>
然后运行之~~,呵呵,调用JSP读取数据库中图片并显示在页面上就这样出来了~~~