【问题标题】:reactive ServerHttpResponse how to return jpg?反应式ServerHttpResponse如何返回jpg?
【发布时间】:2018-10-26 02:01:59
【问题描述】:

我的控制器代码:

@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 内容类型:image/jpeg,

为什么会这样,图片在哪里?

【问题讨论】:

  • 其他用户将您的问题标记为低质量和需要改进。我重新措辞/格式化您的输入,使其更容易阅读/理解。请查看我的更改以确保它们反映您的意图。但我认为你的问题仍然无法回答。 现在应该edit你的问题,添加缺失的细节(见minimal reproducible example)。如果您对我有其他问题或反馈,请随时给我留言。
  • 你似乎从来没有在你的函数中返回任何东西。
  • @TA 那我应该返回什么?

标签: java spring-mvc spring-webflux


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-09-27
    • 1970-01-01
    • 2014-06-23
    • 2021-01-30
    • 2021-07-05
    • 1970-01-01
    • 2017-10-19
    • 2020-10-23
    • 1970-01-01
    相关资源
    最近更新 更多