简体   繁体   中英

reactive ServerHttpResponse how to return jpg?

My controller code:

@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);
}

}

I receive

localhost:8080/verify", return content-length: 0 Content-Type: image/jpeg,

Why is that, and where is the picture?

This will work fine! I already used it in my project:

 @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));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM