2012-02-01 125 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。

相關問題