Java Base64解码错误及解决方法
更新时间:2018年02月17日 14:26:48 投稿:laozhang
本篇文章给大家从一个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。最后发现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();
}
相关文章
MapStruct内部错误:NullPointerException的解决方案
在Java开发中,MapStruct是一个非常流行的对象映射工具,它通过注解处理器在编译时生成映射代码,极大地简化了对象之间的转换操作,本文将详细分析一个常见的MapStruct内部错误——NullPointerException,并提供一系列解决方案,需要的朋友可以参考下2025-02-02
JUC循环屏障CyclicBarrier与CountDownLatch区别详解
这篇文章主要为大家介绍了JUC循环屏障CyclicBarrier与CountDownLatch区别详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-12-12


最新评论