JavaBase64解码错误及解决⽅法
问题提出:
⾃⼰在做⼀个⼩⽹站充当练⼿,但是前端图⽚经过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 = Decoder();
try (OutputStream out = new String())) {
data = decoder.decode(src);
out.write(data);
String();
} catch (IOException e) {
throw new IOException();
}
}
java.lang.IllegalArgumentException: Input byte array has wrong 4-byte ending unit
以上是相关的异常信息。我试图将前端的base64码粘贴到记事本然后⾃⼰在试着解码,也是同样问题。
解决办法:
IllegalArgumentException:⾮法参数异常,
试下这个,应该可以。
springmvc面试教程给你讲述下过程:
去了stackoverflow,debug。最后发现data为null,,加油吧,我们需要学的还很多
下次遇到问题debug下,看是哪条代码出现问题了,通过回答你,我也学到了很多
关键点在这⾥: throw new IOException();
try (OutputStream out = new String())) {
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 = Decoder().decode(src);
try (OutputStream out = new String())) {      out.write(data);
} catch (IOException e) {
e.printStackTrace();
}
String();
}
补充另外⼀种常⽤关闭资源:
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 = Decoder();
try {
out = new String());
data = decoder.decode(src);
out.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
String();
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。