修改JFreeChart 图片的存放路径

/**

**QQ:252574345

**MSN:[email protected]

*/

 

跟踪发现,JFreeChart会把生成的图片,默认放在应用服务器的temp目录下,有的时候我们是不能放在该目录下的,需要改变这个存放路径

发现jfreechart的ServletUtilities类里有

    protected static void createTempDir() {
        String tempDirName = System.getProperty("java.io.tmpdir");
        if (tempDirName == null) {
            throw new RuntimeException("应用服务器目录下不存在temp目录或该目录无法创建");
        }

        // create the temporary directory if it doesn't exist
        File tempDir = new File(tempDirName);
        if (!tempDir.exists()) {
            tempDir.mkdirs();
        }
    }

该方法创建了默认的图片存放路径

在该类的saveChartAsPNG() 和saveChartAsJPEG () 里被调用,产生图形,因此我们的思路就是将ServletUtilities的saveChartAsPNG() 和saveChartAsJPEG () 这2个方法改造成自己定义的方法

修改前源文件如下:

    public static String saveChartAsJPEG(JFreeChart chart, int width,
            int height, ChartRenderingInfo info, HttpSession session)
            throws IOException {

        if (chart == null) {
            throw new IllegalArgumentException("Null 'chart' argument.");  
        }
        //注意,源文件使用了默认路径
        ServletUtilities.createTempDir();
        String prefix = ServletUtilities.tempFilePrefix;
        if (session == null) {
            prefix = ServletUtilities.tempOneTimeFilePrefix;  
        }
        File tempFile = File.createTempFile(prefix, ".jpeg",
                new File(System.getProperty("java.io.tmpdir")));
        ChartUtilities.saveChartAsJPEG(tempFile, chart, width, height, info);
        if (session != null) {
            ServletUtilities.registerChartForDeletion(tempFile, session);
        }
        return tempFile.getName();

    }

 

修改后如下:

    public static String saveChartAsJPEG(JFreeChart chart, int width,
            int height, ChartRenderingInfo info, HttpSession session)
            throws IOException {

//从application中读取出临时文件目录,我事先已经在系统启动时,创建了目录
     
       File tempDr=(File)session.getServletContext().getAttribute("tempDirectory");

      
      
        if (chart == null) {
            throw new IllegalArgumentException("chart 对象为空");  
        }
       
        UIServletUtilities.createTempDir();
        String prefix = UIServletUtilities.tempFilePrefix;
        if (session == null) {
            prefix = UIServletUtilities.tempOneTimeFilePrefix;  
        }
        File tempFile = File.createTempFile(prefix, ".jpeg", tempDr);
        ChartUtilities.saveChartAsJPEG(tempFile, chart, width, height, info);
        if (session != null) {
         UIServletUtilities.registerChartForDeletion(tempFile, session);
        }
        return tempFile.getName();

    }

 

接下来就可以使用

String filename = ServletUtilities.saveChartAsJPEG(chart, 800, 600, info, session);
String graphURL = request.getContextPath() + "/DisplayChart?filename=" + filename;

来生成图形了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章