后台向前端一次返回多張Base64圖片


最近遇到一個后台需要向前端返回多張圖片的業務,因為沒有經驗,搞了好一會。最終的解決方法是:

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 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM