如何为 Jfree 图表设置 Content-Length 以响应 header?

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

我有一个正在创建 jfree 图表的 servlet。默认情况下,它返回 tranfer-encoding 作为分块。但是我必须在响应 header.

中设置 Content-Length
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);

按照建议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()确定编码图像数组的字节长度:

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

稍后,您可以write()将编码后的图片输出到流中:

out.write(b);