Send Image Servlet to Client Example

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

web.xml entry for WantedImage Servlet

Servlet File Name:

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 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.


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


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


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

Leave a Reply

Your email address will not be published. Required fields are marked *