Can't get any output from this servlet... what's wrong?
843836May 21 2004 — edited May 21 2004Hey everyone,
I have to put together this servlet as a quick hack for a proof of concept. Problem is, I can't seem to get it to print out any binary data.
When I uncomment the lines:
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<H1><IMG SRC=\"" + temp + "\"></H1>");
my code prints out the image tag and the image displays properly in the browser. But when I comment those lines out, I can't seem to get any binary response, even if I call this servlet from an HTML image tag such as:
<IMG SRC="/RandomImage" ALT="">
Can anyone give me some insight as to why this is?
Thanks!
Code below:
-----------------------------------
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RandomImage extends HttpServlet {
public String DIRNAME = "./../../../../../../temp/gfx/";
public void service (
javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)
throws javax.servlet.ServletException, java.io.IOException {
ServletContext application = getServletConfig().getServletContext();
String msg = "";//#Either the IMG tag or message to be returned.
File dir = new File(application.getRealPath(DIRNAME));
Vector images = new Vector(); //#Holds the list of images to choose randomly from.
int x = 0; //#Loop index
int y = 0; //#Counts the number of images.
File[] files = dir.listFiles();
if (dir.isDirectory()) {
for (x=0; x<files.length; x++) {
if (files[x].isFile()) {
images.add(y,files[x].toString());
y +=1;
}
}
if (images.size() > 0) {
String temp = images.get((int) Math.round(Math.random() * (y-1))).toString();
/* PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<H1><IMG SRC=\"" + temp + "\"></H1>");
*/ OutputStream os = response.getOutputStream();
File f1 = new File(application.getRealPath(temp));
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f1));
byte[] buf = new byte[1024];
response.setHeader("Pragma", "Pragma: no-cache");
response.setContentType("Content-type: image/gif");
while((x = in.read(buf,0,buf.length)) != -1) {
os.write(buf,0,x);
}
os.flush();
os.close();
in.close();
} else {
}
} else {
}
}
}