使用Base64將字節數組編碼成字符串,或者將字符串解碼成字節數組


一、根據圖片的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

 


免責聲明!

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



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