Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Servlet to stream image using IMG tag

Thread Tools

Servlet to stream image using IMG tag

Posts: n/a
Using some examples I found on the web, I put together the following
servlet to stream an image to a web page.

private void doGet( HttpServletRequest req, HttpServletResponse
res )
throws ServletException, IOException {

ServletContext sc = getServletContext();
String filename = "/public/web/testimage.jpg";

String mimeType = sc.getMimeType(filename);
if (mimeType == null) {
sc.log("Could not get MIME type of "+filename);

File file = new File(filename);

FileInputStream in = new FileInputStream(file);
OutputStream out = res.getOutputStream();

System.out.println("File Name: " + filename );
System.out.println("MIME Type: " + mimeType );
System.out.println("File Length: " + (int)file.length());

byte[] buf = new byte[1024];
int count = 0;
while ((count = >= 0) {
out.write(buf, 0, count);

The following lines in my web.xml file are related to this servlet.

<servlet-name>Image Servlet</servlet-name>

<servlet-name>Image Servlet</servlet-name>


If I use the URL of /testApp/image/1, it processes the servlet fine
and I get the image in my browser.

However, if I put "/testApp/image/1" as the src in an IMG tag inside
the jspx file, I get nothing.
<img src='/testApp/image/1' border='2' alt='my image'/>

I have the servlet setup to log some information in the catalina.out
log. Here is that output.
File Name: /public/web/testimage.jpg
MIME Type: image/jpeg
File Length: 42946

File Name: /public/web/testimage.jpg
MIME Type: image/jpeg
File Length: 42946

The first occurence is when I run this servlet directly from the URL.
The second is when I associate it with the IMG tag. Note they are
both identical which would indicate that the servlet is executing
fine, it just seems that the output is getting lost when I try to put
this in the IMG tag.

Any help would be appreciated.

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
[Servlet] how to send a stream to servlet doPost =?utf-8?B?6L65IOaxnw==?= Java 3 09-14-2007 02:17 PM
servlet: writing to servlet stream that is closed Pawel Java 2 04-12-2006 01:44 PM
how do u invoke Tag b's Tag Handler from within Tag a's tag Handler? shruds Java 1 01-27-2006 03:00 AM
how to download img from html img tag ASP .Net 2 04-27-2005 06:25 PM
Servlet question(Tomcat, web.xml, servlet-class, servlet-name) circuit_breaker Java 2 04-04-2004 03:26 AM