反应性ServerHttpResponse如何返回jpg?

时间:2018-10-26 02:02:00

标签: java spring-mvc spring-webflux

我的控制器代码:

@RestController
public class CaptchaService {

   @GetMapping(value="/verify")
   public void captchaService(ServerHttpResponse response, WebSession webSession) throws IOException {
       BufferedImage image = new BufferedImage(61, 20, BufferedImage.TYPE_INT_RGB);
       Graphics g = image.getGraphics();
       Random r = new Random();
       g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
       g.fillRect(0, 0, 61, 20);
       String code = getNumber();
       webSession.getAttributes().put("captcha", code);
       g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
       g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
       g.drawString(code, 5, 18);
       response.getHeaders().setContentType(MediaType.IMAGE_JPEG);
       OutputStream os = response.bufferFactory().allocateBuffer().asOutputStream();
       ImageIO.write(image, "jpeg", os);
}

}

我收到

  

localhost:8080 / verify”,返回内容长度:0   内容类型:图片/ jpeg,

那是为什么,图片在哪里?

1 个答案:

答案 0 :(得分:0)

这会很好!我已经在项目中使用了它:

 @GetMapping("/world")
    public Mono<Void> world(ServerWebExchange exchange) throws Exception {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().setContentType(MediaType.IMAGE_JPEG);
        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
        fileToByte(new File("F:\\1.jpg"));
        DataBuffer dataBuffer = dataBufferFactory.wrap(bytes);
        return response.writeWith(Flux.just(dataBuffer));
    }