問題提出:
自己在做一個小網站充當練手,但是前端圖片經過base64加密后傳往后端在解碼。但是一直都有問題,請大神賜教
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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(); } } |
1
|
java.lang.IllegalArgumentException: Input byte array has wrong 4 - byte ending unit |
以上是相關的異常信息。我試圖將前端的base64碼粘貼到記事本然后自己在試著解碼,也是同樣問題。
解決辦法:
IllegalArgumentException:非法參數異常,
試下這個,應該可以。
給你講述下過程:
去了stackoverflow,debug。最后發現data為null,,加油吧,我們需要學的還很多
下次遇到問題debug下,看是哪條代碼出現問題了,通過回答你,我也學到了很多
關鍵點在這里: throw new IOException();
1
2
3
4
5
6
7
|
try (OutputStream out = new FileOutputStream(newPath.toString())) { out.write(data); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException( "異常是這么拋出的" ); //throw new RuntimeException(e); } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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(); } |
補充另外一種常用關閉資源:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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(); } |