Java Base64解碼錯誤及解決方法
問題提出:
自己在做一個小網站充當練手,但是前端圖片經過base64加密后傳往后端在解碼。但是一直都有問題,請大神賜教
public static String base64ToImg(String src) throws IOException {
String uuid = UUID.randomUUID().toString();
StringBuilder newPath = new StringBuilder(IMG_ROOT_PATH);
newPath.append(separator).
append(uuid).
append(IMG_SUFFIX);
if(src == null){
return null;
}
byte[] data = null;
Base64.Decoder decoder = Base64.getDecoder();
try (OutputStream out = new FileOutputStream(newPath.toString())) {
data = decoder.decode(src);
out.write(data);
return newPath.toString();
} catch (IOException e) {
throw new IOException();
}
}
java.lang.IllegalArgumentException: Input byte array has wrong 4-byte ending unit
以上是相關的異常信息。我試圖將前端的base64碼粘貼到記事本然后自己在試著解碼,也是同樣問題。
解決辦法:
IllegalArgumentException:非法參數異常,
試下這個,應該可以。
給你講述下過程:
去了stackoverflow,debug。最后發(fā)現data為null,,加油吧,我們需要學的還很多
下次遇到問題debug下,看是哪條代碼出現問題了,通過回答你,我也學到了很多
關鍵點在這里: throw new IOException();

try (OutputStream out = new FileOutputStream(newPath.toString())) {
out.write(data);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("異常是這么拋出的");
//throw new RuntimeException(e);
}
public static String base64ToImg(String src) throws IOException {
String uuid = UUID.randomUUID().toString();
StringBuilder newPath = new StringBuilder("xx");
newPath.append("xx").
append(uuid).
append("xx");
if (src == null) {
return null;
}
byte[] data = Base64.getDecoder().decode(src);
try (OutputStream out = new FileOutputStream(newPath.toString())) {
out.write(data);
} catch (IOException e) {
e.printStackTrace();
}
return newPath.toString();
}
補充另外一種常用關閉資源:
public static String base64ToImg(String src) throws IOException {
String uuid = UUID.randomUUID().toString();
StringBuilder newPath = new StringBuilder("xx");
newPath.append("xx").
append(uuid).
append("xx");
if (src == null) {
return null;
}
byte[] data = null;
OutputStream out = null;
Base64.Decoder decoder = Base64.getDecoder();
try {
out = new FileOutputStream(newPath.toString());
data = decoder.decode(src);
out.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
return newPath.toString();
}
相關文章
springboot獲取properties屬性值的多種方式總結
這篇文章主要介紹了springboot獲取properties屬性值的多種方式總結,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
解決springboot整合cxf-jaxrs中json轉換的問題
這篇文章主要介紹了解決springboot整合cxf-jaxrs中json轉換的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
Spring?Cloud中Sentinel的兩種限流模式介紹
如何使用Sentinel做流量控制呢?這篇文章就來為大家詳細介紹了Spring?Cloud中Sentinel的兩種限流模式,感興趣的小伙伴可以跟隨小編一起學習一下2023-05-05

