最近遇到一个后台需要向前端返回多张图片的业务,因为没有经验,搞了好一会。最终的解决方法是:
1、将图片用for循环从内存读出
2、将图片编码成Base64,并存储到数组ArrayList<String>中
3、返回给前端编码好的图片,前端代码依次解析即可
代码如下:
1 @RequestMapping(value = "/getComponentPicture", method = RequestMethod.POST) 2 @ApiOperation(value = "getComponentPicture", httpMethod = "POST", notes = "查询车辆零件图片") 3 @ResponseBody 4 public ArrayList<?> getComponentPicture( 5 @ApiParam(value = "零件ID", required = true) @RequestParam(value = "componentid", required = true) String componentid, 6 @ApiParam(value = "车主token", required = true) @RequestParam(value = "token", required = true) String token) { 7 try { 8 ArrayList<String> picture = new ArrayList<>(); 9 if (validToken(token)) { 10 List<T415_car_components_pic> list = manufactService.queryComponentPicpath(componentid); 11 if(list.isEmpty()){ 12 picture.add("PIC IS NULL"); 13 return picture; 14 }else{ 15 for(T415_car_components_pic pic:list){ 16 String picpath = pic.getPicpath(); 17 byte[] bt = fileManager.readFile(picpath); 18 String base64str = Base64.encodeBase64String(bt); 19 //import org.apache.commons.codec.binary 20 picture.add("data:image/jpg;base64,"+base64str); 21 } 22 return picture; 23 } 24 }else{ 25 picture.add("invalidToken"); 26 return picture; 27 } 28 }catch (Exception e) { 29 logger.error("", e); 30 String bt = new String("HttpStatus.BAD_REQUEST"); 31 ArrayList<String> err = new ArrayList<>(); 32 err.add(bt); 33 return err; 34 } 35 }