1. 問題描述
- 因需調用第三方公司的圖像識別接口,入參是:證件類型、圖像類型、圖片base64字符串,采用http+json格式調用。
- 本來采用的方式是:前端對圖片做base64處理,后端組裝下直接調用第三方接口,然后將結果返回給前端展示。然而聯調過程中,發現前端對圖片轉換base64字符串后,大小擴了近一倍,傳輸到后台后,存在識別不准確,數據丟失的情況,字符太多,后端調試也比較麻煩。
2. 解決方案
更改前后端調用方式,采用前端不進行Base64處理,使用文件上傳到后端不落地,直接讀取文件流,轉換成base64字符后,再調用第三方圖片識別接口的方式。
2.1 controller接收前端上傳文件
@RequestMapping(value = "/getTestByFile", method = RequestMethod.POST)
public Object getTestByFile(@RequestParam MultipartFile file, String cardType, String imgtype) {
try {
Object result = testService.getTestByFile(file, cardType, imgtype);
return new ResponseEntity(result, HttpStatus.OK);
} catch (Exception e) {
logger.error("接口", e.getMessage());
return new ResponseEntity("調用接口(" + e.getMessage() + ")", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
2.2 service讀取文件流並轉換Base64字符
public Object getTestByFile(MultipartFile file, String cardType, String imgtype) throws Exception {
String imageBase64 = generateBase64(file);
/**
無關代碼,刪除
**/
return imageBase64;
}
public String generateBase64(MultipartFile file) throws Exception {
if (file == null || file.isEmpty()) {
throw new RuntimeException("圖片不能為空!");
}
String fileName = file.getOriginalFilename();
String fileType = fileName.substring(fileName.lastIndexOf("."));
if (!".jpg".equals(fileType) && ".png".equals(fileType)) {
throw new BizException("圖片格式僅支持JPG、PNG!");
}
byte[] data = null;
try {
InputStream in = file.getInputStream();
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}