java對文件的二進制流base64編碼解碼


1.java對文件的二進制流base64編碼解碼

一般保存文件的時候選擇的方式是將url存進數據庫。今天遇到一個對接傳文件流的二進制base64編碼,簡單記錄一下。

 

依賴於commons-io包和commons-codec包。

 編碼的方法如下:

    public static String encodeFile(File file) throws IOException {
        byte[] readFileToByteArray = FileUtils.readFileToByteArray(file);
        return Base64.encodeBase64String(readFileToByteArray);
    }

    public static String encodeFile(String filePath) throws IOException {
        return encodeFile(new File(filePath));
    }

 

解碼的方法如下:(FileUtils會自動創建文件)

    public static void decodeFile(String codes, File file) throws IOException {
        byte[] decodeBase64 = Base64.decodeBase64(codes);
        FileUtils.writeByteArrayToFile(file, decodeBase64);
    }

    public static void decodeFile(String codes, String filePath) throws IOException {
        decodeFile(codes, new File(filePath));
    }

 

補充:有時候將圖片進行base64編碼之后存庫可以用下面方式進行顯示

<img src="data:image/jpeg;base64,${codes}"/>

 


免責聲明!

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



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