Search code examples
httpresponsejfreechart

How to set Content-Length in response header for Jfree chart?


I have a servlet which is creating the jfree chart. By default it is returning tranfer-encoding as chunked. But I have to set the Content-Length in the response header.

final JFreeChart chart = ChartController.createChart();

          final int chartWidth = ChartUtils.calculateWidth(request);
          final int chartHeight = ChartHelper.getQuickViewChartHeight();

          final ServletOutputStream out = response.getOutputStream();
          response.setContentType("image/png");       
          ChartUtilities.writeChartAsPNG(out, chart, chartWidth, chartHeight);

Solution

  • As suggested here, it's not meaningful to set the content-length header and also use chunked transfer encoding. In either case, as outlined here, you can use ChartUtilities.encode() to determine the byte length of the encoded image array:

    byte[] b = ChartUtilities.encode(chart.createBufferedImage(chartWidth, chartHeight));
    int imageLength = b.length;
    

    Later, you can write() the encoded image to the output stream:

    out.write(b);