2012-02-01 20 views
0

MySQL DBからイメージを取得する必要があります。 どこかからコードスニペットを取得しましたが、jQueryパネルに画像を正しく表示できませんでした。 コードは新しいJSPページで実行されます。 アプリケーションでoutputstreamを効果的に使用する方法を教えてもらえますか?JSPでDBからイメージを表示する方法は?

私が持っているコードは次のとおりです。

<% @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に拡張されたクラスを作成し、そこにあるコードをdoGet()メソッドに移動します。最後にJSPの代わりにそのサーブレットを呼び出します。

関連する問題