Wrox Home  
Search P2P Archive for: Go

  Return to Index  

servlets thread: Writing image & text via ServletOutputStream


Message #1 by "Hosea Ho" <comitdo@y...> on Mon, 13 Jan 2003 09:38:49
> Seperately, I have tried successfully writing image and text(each 
s> eperately) to browser via ServletOutputStream.

> However, when I tried to write both image and text together
t> o browser (see code below) Only the image appears. 

> ******CODE HERE*********

> import java.io.*;
i> mport javax.servlet.*;
i> mport javax.servlet.http.*;

> public class PictureAndText extends HttpServlet{

> 	public void doGet(HttpServletRequest request,
	>                   HttpServletResponse response) throws
	>                   ServletException, IOException
	> {

> 		try{
	> 			response.setContentType("text/html");
	> 			ServletOutputStream outout = 
r> esponse.getOutputStream();

> 				//read image from file and write to browser
	> 			File f = new File("C:\\triangle.jpg");
	> 			InputStream is = new FileInputStream(f);

> 				int num = is.read();
	> 			while(num!=-1){
	> 			outout.write(num);
	> 				num = is.read();
	> 			}

> 				//read text and write text to browser
	> 			String str = "BINGO BINGO";
	> 			byte[] byteStr = str.getBytes();
	> 			for(int x=0; x<byteStr.length; x++){
	> 				outout.write(byteStr[x]);
	> 			}

> 			}
	> 		catch(Exception e){
	> 			System.out.println(e);
	> 	}
	> }
}> 

> How do I get the image and text to appear in the browser page?

> Thank you.
H> osea

in short:
When you specify "text/html" in response header the WWW browser expects 
such code not an image. 
Include <IMG> tag within generated html (such a tag may refer to an image 
generated by servlet). 
Using servlet to generate image one must provide proper response header 
("image/jpeg" for example).

Igor

  Return to Index