jQuery in Action, 3rd edition
The moose likes Servlets and the fly likes Download image from servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Download image from servlet" Watch "Download image from servlet" New topic

Download image from servlet

Ramesh Sengani
Ranch Hand

Joined: Nov 23, 2011
Posts: 36

I am working in site where i want to show advertisement images. I was planned to show that by using servlet.

I made following code. but its taking so mach time to download images.

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

resp.setHeader("Content-length", "" + 900000);
resp.setHeader("Content-Disposition","attachment; filename=\"ads.jpg\"");

/* FileInputStream inputStream = null;

File file = new File("http://localhost:8080/Test/images/ad1.jpg");
*/InputStream inp = null;
ServletContext context = getServletContext();

inp = context.getResourceAsStream("/images/Basketball.png");
/* InputStreamReader isr = new InputStreamReader(inp);
BufferedReader reader = new BufferedReader(isr);*/
byte[] buffer = new byte[90000];
int bytesRead =0;// buffer.length;
int i = 0;
bytesRead= inp.read(buffer);
System.out.println(" i: " + ++i + " byts Read " + bytesRead);

} while (bytesRead == buffer.length);

System.out.println(" flush done");
if(inp != null)

System.out.println(" finally complete ");


Please advice or give suggestion on this.

Thanks in advance...
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13018
If this image is supposed to show in a HTML page, why are you sending as "attachment"

Does your code really say:

if so, why.

resp.setHeader("Content-length", "" + 900000);

Sending images works much better if you set the content-length to the actual file size.

Sending image bytes from a servlet should be quite fast - what time delay are you observing?

Ramesh Sengani
Ranch Hand

Joined: Nov 23, 2011
Posts: 36
Thanks william,

Now its working fine.

I removed

resp.setHeader("Content-length", "" + 900000);

I agree. Here's the link: http://aspose.com/file-tools
subject: Download image from servlet
It's not a secret anymore!