2012-02-01 86 views
0

我需要从MySQL DB中检索图像。 我从某处获取了代码片段,但无法在jQuery面板中正确显示图像。代码在新的JSP页面中运行。 谁能告诉我如何在我的应用程序中有效地使用outputstream?如何在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(); 
    } 
} 
%> 

回答

0

JSP是这个错误的工具。 JSP是一种视图技术。 <% %>以外的任何空格也将被打印/发送到响应。在你的情况下,确切地说,空白会影响图像的二进制完整性,并且因此图像最终被破坏并且不可修复。

你基本上有2个选项。

  1. 简单/偷懒的办法:删除所有,我真的是所有,外<% %>空白,包括换行符。

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

相关问题