java 以 HTML 和 JSP 代码显示图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1232591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:44:57  来源:igfitidea点击:

Displaying image in HTML and JSP code

javajspjdbc

提问by BalusC

How can I display image from database in HTML and JSP code? I wrote this code in JSP.

如何以 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> 

回答by BalusC

Images in HTML are to be represented using the <img>element. The <img>element has a srcattribute which should point to an URL which returns an image. That URL can in this particular case just point to a Servletwhich gets an InputStreamof the image from some datasource (e.g. from local disk file system using FileInputStream, or from the DB using ResultSet#getBinaryStream()) and writes it to the OutputStreamof the response the usual Java IOway.

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

Thus, you basically need to change your HTML to include the following:

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

<img src="images?id=1">

Then create a Servletwhich is mapped on an url-patternof /imagesand implement the doGet()roughly like follows:

然后创建一个Servlet映射到一个url-patternof/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) {}
}

That should be it.

应该是这样。

I of course assume that the imagetable in your database already has the (self-descriptive) columns content_type, content_lengthand file_name, otherwise you'll need to substitute the first with "image", leave the second away (or replace with Blob#length()if the database in question supports it) and hardcode a (random) name for the third.

我当然假设image在你的数据库表中已有的(自我描述)列content_typecontent_length并且file_name,否则你将需要替换先用"image",离开第二个客场(或更换Blob#length(),如果有问题支持它的数据库)和为第三个硬编码一个(随机)名称。

Another (slightly different and covering error handling) examples of such an ImageServletcan be found in this article.

ImageServlet可以在本文中找到此类的另一个(略有不同并涵盖错误处理)示例。

回答by Niko

you have to use another method inline images:

您必须使用另一种方法内联图像

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

make sure to base64 encode it. it will not work with ie6 or ie7 but should be fine with all other browsers

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