java base64解码出错_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();

b5d5e1a91eac1c58679c3964858cac6f.png

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();

}

希望与广大网友互动??

点此进行留言吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值