Binary stream decoding base64 encoding of the file 1.java
When selecting a general way is to save the file url deposit into the database. Today encounter a stream of binary file transfer docking base64 encoding, simply record it.
It depends on commons-io package and the package commons-codec.
The coding method is as follows:
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)); }
Decoding method is as follows: (FileUtils will automatically create a file)
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)); }
Added: Sometimes the picture after base64 encoding deposit library can be displayed in the following way
<img src="data:image/jpeg;base64,${codes}"/>