Returning an image stored in mysql with a servlet

To answer this, I created a table images in a test database and stored the esus logo in it.

mysql> create table images (imageuid int(10) not null auto_increment, 
name varchar(30), data blob, length int(6), primary key(imageuid));
Query OK, 0 rows affected (0.12 sec) 
mysql> desc images;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| imageuid | int(10)     |      | PRI | NULL    | auto_increment |
| name     | varchar(30) | YES  |     | NULL    |                |
| length   | int(6)      | YES  |     | NULL    |                |
| data     | blob        | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+

To save an image in this table, use the following code and specify the image at command line. Use a JPG image, as the MIME content type for the servlet we’ll write will be image/jpeg.

Main.java:

import java.util.*;
import java.text.*;
import java.sql.*;
import java.io.*;  
 
public class Main {
   public static void main(String []args) throws Exception {
      try {
         if (args.length != 1) {
            System.out.println("Usage: java Main <img>");
            System.exit(1);
         }
 
         Class.forName("org.gjt.mm.mysql.Driver").newInstance();
         Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/testdb", 
                                                       "",
                                                       "");
 
         File file = new File(args[0]);
         FileInputStream fis=new FileInputStream(file);
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         byte buf[]=new byte[1024];
         int length=-1;
         while((length=fis.read(buf))!=-1) {
            baos.write(buf,0,length);
         }
 
         PreparedStatement insertStmt = conn.prepareStatement(
                                       "INSERT INTO images (name, length, data) " +
                                       "VALUES (?, ?, ?)");
         insertStmt.setString(1, file.getName());
         insertStmt.setInt(2, (int) file.length());
         insertStmt.setBytes(3, baos.toByteArray());
         insertStmt.execute();
 
         fis.close();
         baos.close();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}

The servlet that delivers the image to the browser looks just like any other one, except that the MIME content-type attribute is set to image/jpeg (use image/gif for GIF files). The rest of the code handles the reading of the image from the mysql table given its unique index.

Servlet GetImage.java:

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.sql.*;
import java.io.*;
 
public class GetImage extends HttpServlet {
 
   public void doGet(
       HttpServletRequest request,
       HttpServletResponse response)
         throws ServletException, IOException {
 
     response.setContentType("image/jpeg");
 
     ServletOutputStream sos = response.getOutputStream();
 
     int imageuid = Integer.parseInt(getValues(request, "imageuid"));
     byte[] buf = getImageFromDB(imageuid);
 
     sos.write(buf);
 
     sos.flush();
  }
 
   public byte[] getImageFromDB(int imageuid) {
      byte[] buffer = null;
 
      try {
         Class.forName("org.gjt.mm.mysql.Driver").newInstance();
         Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/testdb", 
                                                       "",
                                                       "");
 
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT name, length, data FROM images " +
                                          "where imageuid = " + imageuid);
      
         if (rs.next()) {
            String name = rs.getString("name");
            int length = rs.getInt("length");
            buffer = rs.getBytes("data");
         }
      }
      catch(Exception e) {
         e.printStackTrace();
      }
 
      return buffer;
   }
 
   public String getValues(HttpServletRequest request, String name) {
      String retVal = "";
 
      String values[] = request.getParameterValues(name);
      if (values == null) {
      }
      else if (values.length == 1) {
         retVal = values[0];
      }
      else {
         for (int i=0; i<values.length; i++) {
            retVal += values[i] + ", ";
         }
      }
 
      return retVal;
   }
}

You can now use the reference to this servlet in an img src HTML tag:

<html>
<body>
<center><img src="http://localhost:8080/servlet/GetImage?imageuid=1"></center>
</body>
</html>