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

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

编写一个servlet,将其映射到像showImage.html这样的showImage.html ,将imagename作为param传递

然后从文件中读取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); 

在发布问题之前进行一些小搜索会有所帮助。 请参阅此处以获取更多帮助

类似下面的代码:

 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: 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("image not found for given id"); 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("Unable To Display image"); out.println("

Image Display Error=" + e.getMessage() + "

"); return; } finally { try { rs.close(); stmt.close(); con.close(); }