一、根據圖片的url將圖片讀入字節輸入流中,然后將字節輸入流中的內容讀取到字節數組中,再將字節數組通過Base64編碼成字符串
Map resultMap = new HashMap(); List<String> images = new ArrayList<>(); //根據采購訂單詳細獲取樣本圖片,轉為字節流 List<AttachFile> fileList = attachFileService.getFileList(inDetailId, "B_IN_DETAIL", "BIDSAMPLE_IMG"); fileList.stream().forEach(file -> { String url = shareFile + "/" + file.getUploadPath() + "/" + file.getCompressedName(); try (InputStream in = new BufferedInputStream(new FileInputStream(url))) { byte[] srcBytes = new byte[in.available()]; in.read(srcBytes); images.add(Base64.getEncoder().encodeToString(srcBytes)); } catch (Exception e) { log.error("圖片轉換流異常:" + e.getMessage()); } }); resultMap.put("IMAGES", images); return resultMap;
二、將JSON字符串轉換成字節數組,然后將字節數組中的內容通過字節輸出流寫入文件中
//將字符串轉換為byte數組 byte[] bytes = Base64.getDecoder().decode(base64.trim()); File file = new File(dir + "/" + fileName); FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos); bos.write(bytes); if (bos != null) { bos.close(); } if (fos != null) { fos.close(); }
引入Base64:
import java.util.Base64