Home > front end >  I use springBoot And Vue , i want send a response to vue , But response always is garbled
I use springBoot And Vue , i want send a response to vue , But response always is garbled

Time:09-21

@Controller
@Slf4j
public class SeckillGoodsController {
    @Autowired
    RedisTemplate redisTemplate;
    @GetMapping("/captcha")
    public void verifyCode(Long userId,Long goodsId, HttpServletResponse response){
        //set Header as pic
        response.setContentType("image/gif");
        // no cookie keep every flush is new captcha
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);//never expires
        //Use a util [enter image description here][1]
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 32, 3);
        redisTemplate.opsForValue().set("captcha:" userId ":" goodsId,captcha.text(),60, TimeUnit.SECONDS);
        try {
            System.out.println(response.getOutputStream().toString());
            captcha.out(response.getOutputStream());
        } catch (IOException e) {
            log.error("Errot",e.getMessage());
        }
    }

}

I send a response to vue.js but use postman test the Body always is captcha, I've set the UTF-8, but it's still wrong [1]: https://i.stack.imgur.com/04RKS.png

CodePudding user response:

  1. this has nothing to do with Spring Boot.

  2. I'm not entirely sure what the ArithmeticCaptcha does but I guess it creates an image and stream it to the response stream

  3. I don't know what you would expect... You are sending binary data (an image) so it is quite normal that you can't read it.

  4. You are setting the content type twice. You can't do that. In addition, it seems to be png so you might want to check it out.

  5. I guess that you want to would like to get a JSON back or similar. In that case, you need to change your code

Here is an example:

@ResponseBody
@RequestMapping("/captcha")
public JsonResult captcha(Long userId, Long goodsId, HttpServletResponse response) throws Exception {
  ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 32, 3);
  String key = "captcha:" userId ":" goodsId
  redisTemplate.opsForValue().set(key, captcha.text(), 60, TimeUnit.SECONDS);
  return JsonResult.ok().put("key", key).put("image", captcha.toBase64());
}

Might need some tweaks to fit 100% your case but this will return a json with a key that is the one you probably will need to match in your next step and the image base64 encoded so it would be (almost) readable.

You can then add the base64 encoded string from the response as the src of your img tag.

  • Related