This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I have a requirement in which I need to display an image which resides on a remote machine using a servlet. I have tried using a servlet in which content -type of response is set to html and displaying the image using the img tag.
But that trial is in vein as this will not work when accessing the servlet from the client machine.
Can anyone please suggest me the way to achieve this??
How are you accessing the image on the remote machine? If the image available via http? If so then an img tag should work. If, on the other hand, the image is not http accessible but is only accessible as a file, your servlet would have to open the image file, read in the contents and place those in the response buffer. In addition, you would have to set the mime type to match the image type.
For example, something like this:
Warning - I transcribed the above from some Groovy code I have that does the same thing, so it has not been tested.
Now, this code cannot go in the same servlet that builds the page. Instead, the servlet that builds the page creates an img tag that references another servlet, and the above code goes into that servlet. (Or it could be the same servlet but with two different outputs based on the input.) [ October 31, 2008: Message edited by: Peter Johnson ]
I would finetune the code a bit more. It is not written quite efficient. It places the whole image in the memory instead of buffering it. If you have a lot of fairly big images and a lot of requests are been fired on the servlet concurrently, then the server may run out of memory sooner or later.