問題提出:
自己在做一個小網站充當練手,但是前端圖片經過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。最後發現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(); }