Send Image Servlet to Client Example


So far all the earlier examples, we used to send text or HTML messages (text/html) to client. Now-a-days, images are also playing important role in client/server communication. For example, you go to Bank and give a self cheque to draw some money. Immediately, the Bank clerk checks your face to know exactly you are withdrawing the money or not (as it is self cheque). Your image is sent by server to the client (here, Bank clerk). It may be required on the server, a Servlet may have to return the image.

Now read Send Image Servlet.
Example on Send Image Servlet

This example illustrates how to send an image to client’s browser from a Servlet.

User enters his name and clicks submit button. The user name is validated and accordingly an image is sent to client.

Note: Before executing this example, see that SNRao.gif file exist in C drive.

Client HTML File Name: WantedImage.html

  
Enter User Name

web.xml entry for WantedImage Servlet


  snrao1
  WantedImage



  snrao1
  /WI

Servlet File Name: WantedImage.java

import java.io.*;		
import javax.servlet.*;
import javax.servlet.http.*;	            

public class WantedImage extends HttpServlet
{
  public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException 
  { 
    res.setContentType("image/gif");             // see different MIME type
    ServletOutputStream sos = res.getOutputStream();// for binary stream of image files

    String userName = req.getParameter("userField");

    if(userName.startsWith("Sure") && userName.endsWith("Rao"))
    {
      File f = new File("c:\\SNRao.gif");
      DataInputStream dis = new DataInputStream(new FileInputStream(f));
      byte[] barray = new byte[(int) f.length()];
      
      try 
      { 
        dis.readFully(barray);           // now the array contains the image
      }
      catch (Exception e) 
      { 
        barray = null; 
      }
      finally 
      { 
        dis.close( ); 
      }
      
      sos.write(barray);                 // send the byte array to client
      sos.close();
    }
  }
}

ServletOutputStream sos = res.getOutputStream();

Image constitutes of binary stream and for binary stream, use always ServletOutputStream (instead of conventional PrintWriter).

File f = new File("c:\\SNRao.gif");
DataInputStream dis = new DataInputStream(new FileInputStream(f));

A java.io.File object is created that includes the image SNRao.gif and this f object is passed to the high-level byte stream DataInputStream constructor.

byte[] barray = new byte[(int) f.length()];

A byte array, barray, is created of length equivalent to the size of the image. f.length() returns the size of the image as long data type and is casted to int. Java Array does not take long size.

dis.readFully(barray);

Read complete image into the array with readFully() method of DataInputStream.

sos.write(barray);

Now send the image to client with write() method of OutputStream inherited by ServletOutputStream. Do not use print() or println() methods of ServletOutputStream.

Client when entered valid user name

Send Image Servlet

Output screen showing image on the Client’s browser

ima1

Pass your comments and suggestion of this tutorial on "Send Image Servlet to Client Example".

Leave a Comment

Your email address will not be published.