JDBC对数据库BLOB字段图片存取及页面JSP显示问题
JDBC插入或更新图片 保存为BLOB字段
import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;public class TestJDBC {private final static String username = "xxx";private final static String password = "yyyyy";private final static String url = "jdbc:oracle:thin:@111.222.333.444:1521:oracas";private final static String driver = "oracle.jdbc.driver.OracleDriver";private Connection conn = null;public Connection getConnection() {try {Class.forName(driver).newInstance();conn = DriverManager.getConnection(url, username, password);} catch (Exception e) {e.printStackTrace();}return conn;}public int update() throws Exception {Connection conn = null;PreparedStatement ps = null;InputStream is = null;int cnt = 0;try {String sqlStr = "update my_table t set t.loc_img = ? where t.id = ? ";conn = getConnection();conn.setAutoCommit(false);ps = conn.prepareStatement(sqlStr);File file = new File("d:\\test3.bmp");is = new BufferedInputStream(new FileInputStream(file));ps.setBinaryStream(1, is, (int) file.length());ps.setString(2, "96C9F1CC15144B65E040070A3BBD46D3");cnt = ps.executeUpdate();conn.commit();conn.setAutoCommit(true);System.out.println("cnt:" + cnt);} catch (Exception e) {e.printStackTrace();} finally {if (is != null) {is.close();}if (ps != null) {ps.close();}if (conn != null) {conn.close();}}return retVal;}public static void main(String[] args) throws Exception {new TestJDBC().update();}}页面JSP获取图片信息
showLocImage.jsp
<%OutputStream os = null;try{String id = request.getParameter("id");IScotomaBO scotomaBO = new ScotomaBO();java.sql.Blob image = scotomaBO.getLocImage(id);if(image != null){int length = (int) image.length();byte[] buf = image.getBytes(1, length);response.setContentType("image/jpeg");os = response.getOutputStream();for (int i = 0; i < buf.length; i++) {os.write(buf[i]);}} else {PrintWriter pw = response.getWriter();pw.print("没有相关图片信息!");}out.clear(); out = pageContext.pushBody(); } catch (Exception e) {e.printStackTrace();} finally {if(os!=null){os.flush();os.close();}}%>让图片显示:
showMain.jsp
function showLocImage(id){//window.open('showLocImage.jsp?id='+id,'xx','height=500, width=800,menubar=no, scrollbars=yes, resizable=yes,location=no, status=no');fiximgwin("showLocImage.jsp?id="+id);}function fiximgwin(url){ var imgwin=window.open('','img','width=50,height=50,scrollbars=yes, resizable=yes'); imgwin.focus();var HTML="<html>\r\n<head>\r\n<title>图片浏览</title>\r\n</head>\r\n<body leftmargin=\"0\" topmargin=\"0\">\r\n<img src=\""+url+"\" onload=\"window.resizeTo(this.width+10,this.height+36);window.moveTo((screen.width-this.width)/2,(screen.height-this.height+300)/2)\">\r\n</body>\r\n</html>"; var doc = imgwin.document;doc.write(HTML); doc.close();} 如何让弹出窗口自适应图片的大小
参考
http://www2.flash8.net/teach/4140.htm