鍍金池/ 問答/Java  HTML/ Java Base64解碼錯誤

Java Base64解碼錯誤

自己在做一個小網(wǎng)站充當練手,但是前端圖片經(jīng)過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:非法參數(shù)異常,

試下這個,應該可以。
給你講述下過程:
去了stackoverflow,debug。最后發(fā)現(xiàn)data為null,,加油吧,我們需要學的還很多
下次遇到問題debug下,看是哪條代碼出現(xiàn)問題了,通過回答你,我也學到了很多
關鍵點在這里: 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();
    }
2017年8月23日 05:47