【问题标题】:How to display an image from the DB in JSP?如何在 JSP 中显示来自数据库的图像?
【发布时间】:2012-02-23 22:30:04
【问题描述】:

我需要从 MySQL 数据库中检索图像。 我从某个地方得到了一个代码 sn-p,但无法在 jQuery 面板中正确显示图像。 代码在新的 JSP 页面中运行。 谁能告诉我如何在我的应用程序中有效地使用输出流?

我的代码是:

<% @page import = "java.sql.*" %>
<% @page import = "java.io.*" %>
<% Blob image = null;
Connection con = null;
byte[] imgData = null;
Statement stmt = null;
ResultSet rs = null;
try {
    Class.forName("com.mysql.jdbc.Driver");
    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/aes", "root", "password");
    stmt = con.createStatement();
    rs = stmt.executeQuery("select PHOTO from tab_1 where name ='" + name + "'");
    if (rs.next()) {
        image = rs.getBlob(1);
        imgData = image.getBytes(1, (int) image.length());
    } else {
        out.println("image not found for given id>");
        return;
    }
    // display the image
    response.setContentType("image/gif");
    OutputStream o = response.getOutputStream();
    o.write(imgData);
    o.flush();
    o.close();
} catch (Exception e) {
    out.println("Unable To Display image");
    out.println("Image Display Error=" + e.getMessage());
    return;
} finally {
    try {
        rs.close();
        stmt.close();
        con.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
%>

【问题讨论】:

    标签: mysql image jsp blob


    【解决方案1】:

    JSP 是错误的工具。 JSP 是一种视图技术。 &lt;% %&gt; 之外的任何空格也将被打印/发送到响应。在您的情况下,正是那个空格会破坏图像的二进制完整性,因此图像最终会被损坏且无法渲染。

    你基本上有两个选择。

    1. 简单/懒惰的方式:删除所有,我的意思是all&lt;% %&gt; 之外的空格,包括换行符。

    2. 使用正确的工具:创建一个扩展 HttpServlet 的类,并将 JSP 中的代码移动到 doGet() 方法中。最后只需调用该 servlet 而不是 JSP。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-18
      相关资源
      最近更新 更多