1.在servlet中上传图片,上传的文件夹是imge在webroot下,主要代码如下

    private void saveImage(HttpServletRequest request, HttpServletResponse response) throws IOException  {
//保存的图片的名称
fileName =System.currentTimeMillis() + ".jpg";
//获得imge文件夹在tomcat中的决定路径,basePath的值是C:\Program Files\Apache Software Foundation\Apache Tomcat 6.0.20\webapps\flexTest\imge
String basePath = request.getSession().getServletContext().getRealPath("/imge/");
filePath = basePath;
System.out.println("保存图片的地址为:"+filePath);
realFilePath = filePath+"\\"+fileName;
// 获得一个图片文件流,我这里是从flex中传过来的
BufferedImage bufferedImage = ImageIO.read(request.getInputStream());
if (bufferedImage != null) {
//保存图片到指定的目录和文件中
ImageIO.write(bufferedImage, "jpeg", new File(filePath , fileName));
}
}

2.当要把上面上传图片通过servlet展示到游览器上时,取的路径如下:

private void printImage(HttpServletRequest request, HttpServletResponse response) throws IOException  {
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
//获得服务器的地址,不能直接获取本机tomcat的绝对路径,不然游览器读取不了指定的图片文件
// basePath的值是http://localhost:8080/flexTest
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
String showFile = basePath+"/imge/"+this.fileName;
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(" <img src="+showFile+">");
out.print("</img>");
System.out.println("有显示图片的地址是"+showFile);
//showFile的值是 http://localhost:8080/flexTest//imge/1299470395060.jpg
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
04-25 13:31
查看更多