天天看點

前後端分離之---圖檔驗證碼

在前後端端分離的項目中圖檔驗證碼怎麼擷取,以及怎麼驗證

擷取驗證碼其實不難,關鍵是後端怎麼驗證此驗證碼?
1. 後端生成圖檔驗證碼,把位元組流發送到前端僞代碼:
           
@RequestMapping(value = "/picture", method =RequestMethod.GET)
    public ResponseEntity<byte[]> picture(@PathVariable String phoneNumber,  HttpServletResponse response) throws IOException {
    //生成驗證碼

    HttpHeaders headers = new HttpHeaders();
    headers.put("pictureId",UUID.randomUUID())//标注唯一性
    //位元組流
    ByteArrayOutputStream baos = new ByteArrayOutputStream();//位元組輸出流
    //之前的方式直接寫到輸出流中
    //ImageIO.write(image, "JPEG", response.getOutputStream());
    //response.getOutputStream().flush();
    //現在傳回位元組數組
    ImageIO.write(image, "JPEG", baos);
    byte[] content = baos.toByteArray();
    return new ResponseEntity<byte[]>(content, null, HttpStatus.OK);
}
           
  1. 後端把pictureId 存到緩存中去,設定一個過期時間.
  2. 前端拿到資料顯示,然後下次請求的時候把pictureId 帶上,供後端驗證

可選的方式

  1. 也可以傳回base64的圖檔編碼,前端直接顯示.更通用些
  2. 前端生成pictureId 發送到後端,可能會産生相同的pictureId (幾率很小)

參考:http://www.cnblogs.com/liminjun88/p/6556493.html