1

javaサーブレットを使用してmysqlデータベースから画像を取得し、HTML imgタグで表示する方法は? また、そのimaタグはテーブル定義内に配置する必要がありますか?

4

2 に答える 2

2

サーブレットを作成し、それを のような URL にマップしshowImage.html、イメージ名をパラメーターとして渡します

<img src="showImage.html?filename=new.jpg">

次に、ファイルから byte[] を読み取り、サーブレット コードの応答 OutputStream に書き込みます。

response.getOutputStream().write(bytes);

ファイルから byte[] を取得するには

 RandomAccessFile f = new RandomAccessFile("c:\images\pic1.png", "r");
 byte[] bytes = new byte[(int)f.length()];
 f.read(bytes);
 response.getOutputStream().write(bytes);
于 2013-01-29T13:02:27.587 に答える
0

以下のコードのようなもの:

public void doGet(HttpServletRequest request, HttpServletResponse response) 
  throws IOException,ServletException {

     Blob image = null;
      Connection con = null;
      Statement stmt = null;
      ResultSet rs = null;
      ServletOutputStream out = response.getOutputStream();
      try {
      Class.forName("com.mysql.jdbc.Driver");
      con = DriverManager.getConnection("jdbc:mysql://127.0.0.0:3306/
       example","root","root"); // localhost:<defaultport>
      stmt = con.createStatement();
      rs = stmt.executeQuery("select image from pictures where  id = '2'");
      if (rs.next()) {
      image = rs.getBlob(1);
      } else {
      response.setContentType("text/html");

      out.println("<font color='red'>image not found for given id</font>");

      return;
      }
      response.setContentType("image/gif");
 InputStream in = image.getBinaryStream();
  int length = (int) image.length();
  int bufferSize = 1024;
  byte[] buffer = new byte[bufferSize];
  while ((length = in.read(buffer)) != -1) {
  out.write(buffer, 0, length);
  }
  in.close();
  out.flush();

} catch (Exception e) {
  response.setContentType("text/html");
  out.println("<html><head><title>Unable To Display image</title></head>");
  out.println("<body><h4><font color='red'>Image Display Error=" + e.getMessage() +
   "</font></h4></body></html>");
  return;
  } finally {
  try {
  rs.close();
  stmt.close();
  con.close();
  }
于 2013-01-29T12:57:28.190 に答える