Knowledgebase: Java/JSP Hosting Plans
Returning an Image in a Servlet
Posted by Customer Service on 25 May 2005 12:41 AM
This example returns to the requestor, an image read from a file:
// This method is called by the servlet container to process a GET request.
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Get the absolute path of the image
ServletContext sc = getServletContext();
String filename = sc.getRealPath("image.gif");

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

// Set content type

// Set content size
File file = new File(filename);

// Open the file and output streams
FileInputStream in = new FileInputStream(file);
OutputStream out = resp.getOutputStream();

// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = >= 0) {
out.write(buf, 0, count);
(334 vote(s))
Not helpful

Comments (0)