web server 是 tomcat,操作系统是unix,使用spring mvc。image文件在“this.imgRootPath”下。 file.exists()返回true,文件大小也能得到,但是无论输出到 http response.outputstream 还是尝试输出到新的文件中,内容都为空。也就是网页显示一个红x,unix本地文件 ("/opt/app/apache-tomcat-6.0.20/test.gif")大小为0。但相同代码,在我本地的windows里面运行正常,这是怎么回事呢?jsp 源码:
<img src="helpimg.do?imgPath=${imgPath}" />
java 源码public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        try {
            String imgName = request.getParameter("imgPath");
            
            File file = new File(this.imgRootPath + "/" + imgName);
            logger.error(file.getAbsolutePath() + ": " + file.exists() + ", " + file.length());
            BufferedImage buffer = ImageIO.read(file);
            
            int pos = imgName.lastIndexOf(".");
            String imgType = imgName.substring(pos + 1);
            response.setContentType("image/" + imgType);
            OutputStream os = response.getOutputStream();
            
            
            ImageIO.write(buffer, imgType, os);
            
            os.flush();
            os.close();
            FileOutputStream fout = new FileOutputStream("/opt/app/apache-tomcat-6.0.20/test.gif");
            ImageIO.write(buffer, imgType, fout);
            fout.flush();
            fout.close();
        }catch(Exception e){
            logger.error(e);
        }
        return null;
    }

解决方案 »

  1.   

    路径问题的话,
    logger.error(file.getAbsolutePath() + ": " + file.exists() + ", " + file.length()); 
    这句输出没有任何出错,exisits()返回true,文件大小也对。
      

  2.   

    确保路径下的文件存在,不为空先
    File file = new File(this.imgRootPath + "/" + imgName);  //???
      

  3.   

    你这么输出没用过,直接用byte的方式输出到流就可以了,没必要还用BufferedImage和ImageIO。
      

  4.   

    调试下来
    加上 这句logger.info(file.canExecute());
    程序执行到这里就不往下走了,但又没有exception.
      

  5.   

    感觉直接在jsp页面上取图片的路径的可行性高一点
      

  6.   

    也就是说在action中传一个路径字符串到jsp显示
      

  7.   

    没有exception,说不定是error。捕获一下Throwable
      

  8.   

    刚发现,unix环境的jdk是1.5的,canExecute()是java 6的方法。