上传文件不落地转Base64字符串

2023-06-14,,

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

上传文件不落地转Base64字符串的相关教程结束。

《上传文件不落地转Base64字符串.doc》

下载本文的Word格式文档,以方便收藏与打印。