以HTML和JSP代码显示图像

时间:2009-08-05 11:13:00

标签: java jsp jdbc

如何在HTML和JSP代码中显示数据库中的图像?我在JSP中编写了这段代码。

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page language="java" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>MindDotEditor posted Data</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="robots" content="noindex, nofollow" />
        <link href="../sample.css" rel="stylesheet" type="text/css" />
        <link rel="shortcut icon" href="../fckeditor.gif" type="image/x-icon" />
    </head>
    <body>

<%
    String url = "jdbc:mysql://localhost:3306/sample";
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;
    String id = (String) session.getAttribute("id");
    int j = Integer.parseInt(id);

    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        con = DriverManager.getConnection(url,"root","root");
        stmt = con.createStatement();
        rs = stmt.executeQuery("SELECT Image_File FROM Images WHERE Image_id = '3' ");
        int i = 1;
        if(rs.next()) {
            Blob len1 = rs.getBlob("Image_File");
            int len = (int)len1.length();
            byte[] b = new byte[len];
            InputStream readImg = rs.getBinaryStream(1);
            int index = readImg.read(b, 0, len);
            System.out.println("index" +index);
            stmt.close();
            response.reset();
            response.setContentType("image/jpg");
            response.getOutputStream().write(b,0,len);
            response.getOutputStream().flush();
        }
    } catch(Exception ex) {
        out.println(ex);
    } finally {
        rs.close();
        stmt.close();
        con.close();
    }
%>

        <br>
        <center><input type="button" value="Print" onclick="window.print();return false;" /></center>
    </body>
</html> 

2 个答案:

答案 0 :(得分:2)

HTML中的图像将使用<img>元素表示。 <img>元素具有src属性,该属性应指向返回图像的URL。在这种特定情况下,该URL只能指向Servlet,它从某个数据源获取图像的InputStream(例如,使用FileInputStream从本地磁盘文件系统获取,或使用{从DB获取{1}})并以通常的Java IO方式将其写入响应的ResultSet#getBinaryStream()

因此,您基本上需要更改HTML以包含以下内容:

OutputStream

然后创建一个<img src="images?id=1"> 映射到Servlet url-pattern并实现/images大致如下:

doGet()

应该是它。

我当然假设数据库中的Image image = imageDAO.find(Long.valueOf(request.getParameter("id"))); response.setContentType(image.getContentType()); response.setContentLength(image.getContentLength()); response.setHeader("Content-Disposition", "inline; filename=\"" + image.getFileName() + "\""); BufferedInputStream input = null; BufferedOutputStream output = null; try { input = new BufferedInputStream(image.getInputStream()); output = new BufferedOutputStream(response.getOutputStream()); byte[] buffer = new byte[8192]; int length; while ((length = input.read(buffer)) > 0) { output.write(buffer, 0, length); } } finally { if (output != null) try { output.close(); } catch (IOException logOrIgnore) {} if (input != null) try { input.close(); } catch (IOException logOrIgnore) {} } 表已经包含(自我描述性)列imagecontent_typecontent_length,否则您将需要用file_name替换第一个,留下第二个(如果有问题的数据库支持,则替换为"image")并硬编码第三个的(随机)名称。

可以在this article中找到此类Blob#length()的另一个(略有不同且涵盖错误处理)示例。

答案 1 :(得分:-1)

你必须使用另一种方法inline images

data:[<mediatype>][;base64],<data>
<img src="data:image/gif;base64,R0lGODlhEAAOALMAAO...." width="16" height="14" alt="embedded folder icon">

确保base64编码。它不适用于ie6或ie7,但应该适用于所有其他浏览器