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}"/>