<!------------ 文件 1.htm 开始--------------------> <html> <head><title>用servlet 显示图片</title></head> <body> <img src="http://localhost:8080/servlet/showimage"> </body> </html> <!------------ 文件 1.htm 结束 ----------------> |
//====================== showimage.java 程序开始 =================================== 在html 调用时只 import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class showimage extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try{ FileInputStream hFile = new FileInputStream("d:\\1.gif"); // 以byte流的方式打开文件 d:\1.gif int i=hFile.available(); //得到文件大小 byte data[]=new byte[i]; hFile.read(data); //读数据 hFile.close(); res.setContentType("image/*"); //设置返回的文件类型 OutputStream toClient=res.getOutputStream(); //得到向客户端输出二进制数据的对象 toClient.write(data); //输出数据 toClient.close(); } catch(IOException e) //错误处理 { PrintWriter toClient = res.getWriter(); //得到向客户端输出文本的对象 res.setContentType("text/html;charset=gb2312"); toClient.write("无法打开图片!"); toClient.close(); } } } |