如何使用java servlet从mysql数据库中检索图像并在HTML img标签中显示?

时间:2013-01-29 12:53:29

标签: java html mysql servlets

如何使用java servlet从mysql数据库中检索图像并在HTML img标签中显示?并且ima标签应该放在表定义中吗?

2 个答案:

答案 0 :(得分:2)

编写一个servlet,将其映射到类似showImage.html的URL,将imagename作为param传递

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

然后从文件中读取byte []并写入servlet代码中的响应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);

答案 1 :(得分: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();
  }