Base64轉byte[]
byte[] bytes = DatatypeConverter.parseBase64Binary("base64字符串");
byte[]轉base64
String base64Str = DatatypeConverter.printBase64Binary(bytes);
除了上面的工具,還有另外兩種工具:
org.apache.commons.codec.binary.Base64;和 java.util.Base64
org.apache.commons.codec.binary.Base64的用法為:
Base64.encodeBase64URLSafeString(bytes[]);
Base64.decodeBase64(base64Content.getBytes());
java.util.Base64的用法為:
Base64.getUrlEncoder().encode(bytes[]);
Base64.getUrlDecoder().decode(base64Content);
推薦使用第二種方式,因為他通過鏈接傳送base64傳的話比較安全,不會因為攜帶特殊字符導致瀏覽器串改base64,從而使文件被破壞。
已在實際工作中驗證,好用!