图片是保存在数据库里的,请问如何在页面上显示?谢谢
我在Action中有以下代码:
byte[] image = rs.getBytes("Image");
request.setAttribute("myimage", image);
请问在view页面中如何显示该图片?谢谢!
[解决办法]
这样做是不对的,网页上无法显示你保存在容器request中的图像数据,要在网页上显示一幅图像,在html中使用img标记:<img border="0" src="图像的网络资源地址">,当浏览器解析到<img border="0" src="图像的网络资源地址">这样一个标记时,浏览器会打开一个到图像的网络资源地址的连接去下载这幅图像,在jsp运行产生的,只能是html/text类型的文本,不可能包含二进制。
要将图像输出到浏览器,可以编写一个servlet,在servlet的doget方法中,设置response对象的contenttype,然后将二进制数输出到response的输出流中:
response.setContentType("image/jpeg");//比如是jpeg图像
byte[] image = rs.getBytes("Image");
response.setContentLength(image.legth);
response.getOutputStream().write( rs.getBytes("Image"));
在网页中就可以这样(假设servlet叫getImage):
<img border="0" src="getImage?imageid=344">
[解决办法]
顶所有楼上!!!再加一个完整点的破烂例子
1) LoadImage.java 用于输出图片(结合jsp或者Servlet来使用)
package com.learn.util;import java.io.BufferedInputStream;import java.io.IOException;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletResponse;import com.learn.db.ConnectionFactory; // 自己实现一个连接工厂类public class LoadImage {/* if exists (select * from sysobjects where id = object_id('ImageContainer') and OBJECTPROPERTY(id, 'IsUserTable') = 1) drop table obj CREATE TABLE [ImageContainer] ( [rid] [int] IDENTITY (1, 1) NOT NULL , [rname] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL , [rpath] [varchar] (500) COLLATE Chinese_PRC_CI_AS NULL , [rfilesize] [int] NULL , [rbinary] [image] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]*/ public void getFileFromDatabaseByRid(int rid, HttpServletResponse response) { String strSQL = null; Connection conn = null; PreparedStatement pstmt = null; ResultSet rst = null; ServletOutputStream sos = null; BufferedInputStream bis = null; try { strSQL = "SELECT * FROM ImageContainer WHERE rid = ?"; conn = ConnectionFactory.getConnection(); // 取得Connection,代码略 pstmt = conn.prepareStatement(strSQL); pstmt.setInt(1, rid); rst = pstmt.executeQuery(); if (rst.next()) { bis = new BufferedInputStream(rst.getBinaryStream("rbinary")); sos = response.getOutputStream(); byte[] b = new byte[10 * 1024]; int len = 0; while ((len = bis.read(b)) != -1) { sos.write(b, 0, len); } bis.close(); sos.flush(); sos.close(); } else { System.out.println("picture dose not exist!"); } } catch (IOException ioe) { ioe.printStackTrace(); } catch (SQLException sqle) { sqle.printStackTrace(); } finally{ ConnectionFactory.close(rst); ConnectionFactory.close(pstmt); ConnectionFactory.close(conn); } }}