zoukankan      html  css  js  c++  java
  • servlet上传图片 服务器路径(转)

        private void saveImage(HttpServletRequest request, HttpServletResponse response) throws IOException  {   
                //保存的图片的名称  
                fileName =System.currentTimeMillis() + ".jpg";    
               //获得imge文件夹在tomcat中的决定路径,basePath的值是C:Program FilesApache Software FoundationApache Tomcat 6.0.20webappsflexTestimge  
                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();  
  • 相关阅读:
    Supervisor 管理进程,Cloud Insight 监控进程,完美!
    【灵魂拷问】你为什么要来学习Node.js呢?
    Web数据交互技术
    请求与上传文件,Session简介,Restful API,Nodemon
    Express服务器开发
    HTTP协议,到底是什么鬼?
    大学我都是自学走来的,这些私藏的实用工具/学习网站我贡献出来了,建议收藏精品推荐
    Node.js安装使用-VueCLI安装使用-工程化的Vue.js开发
    React开发环境准备
    【可视化】Vue基础
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/4759353.html
Copyright © 2011-2022 走看看