servlet上传图片 服务器路径

来源:互联网 发布:知你所想,予你所求歌词 编辑:程序博客网 时间:2024/05/21 17:16
1.在servlet中上传图片,上传的文件夹是imge在webroot下,主要代码如下 
Java代码  收藏代码
  1. private void saveImage(HttpServletRequest request, HttpServletResponse response) throws IOException  {   
  2.         //保存的图片的名称  
  3.         fileName =System.currentTimeMillis() + ".jpg";    
  4.        //获得imge文件夹在tomcat中的决定路径,basePath的值是C:\Program Files\Apache Software Foundation\Apache Tomcat 6.0.20\webapps\flexTest\imge  
  5.         String basePath = request.getSession().getServletContext().getRealPath("/imge/");  
  6.         filePath = basePath;  
  7.         System.out.println("保存图片的地址为:"+filePath);  
  8.         realFilePath = filePath+"\\"+fileName;  
  9.         // 获得一个图片文件流,我这里是从flex中传过来的  
  10.         BufferedImage bufferedImage = ImageIO.read(request.getInputStream());    
  11.        if (bufferedImage != null) {    
  12.            //保存图片到指定的目录和文件中  
  13.            ImageIO.write(bufferedImage, "jpeg"new File(filePath , fileName));    
  14.        }    
  15.    }    
  16.    


2.当要把上面上传图片通过servlet展示到游览器上时,取的路径如下: 
Java代码  收藏代码
  1. private void printImage(HttpServletRequest request, HttpServletResponse response) throws IOException  {     
  2.         response.setContentType("text/html");  
  3.         request.setCharacterEncoding("utf-8");  
  4.         PrintWriter out = response.getWriter();  
  5.         //获得服务器的地址,不能直接获取本机tomcat的绝对路径,不然游览器读取不了指定的图片文件  
  6.         // basePath的值是http://localhost:8080/flexTest  
  7.         String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";  
  8.         String showFile = basePath+"/imge/"+this.fileName;  
  9.         out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");  
  10.         out.println("<HTML>");  
  11.         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");  
  12.         out.println("  <BODY>");  
  13.         out.print("    This is ");  
  14.         out.print(" <img src="+showFile+">");  
  15.         out.print("</img>");  
  16.         System.out.println("有显示图片的地址是"+showFile);  
  17.        //showFile的值是    http://localhost:8080/flexTest//imge/1299470395060.jpg  
  18.         out.println(", using the POST method");  
  19.         out.println("  </BODY>");  
  20.         out.println("</HTML>");  
  21.         out.flush();  
  22.         out.close();  
  23.    }    
转载自:http://www.cnblogs.com/flyingcloude/archive/2013/01/02/2841946.html
原创粉丝点击