饲妖,中国美院教务网,cz456
问题提出:
自己在做一个小网站充当练手,但是前端图片经过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(); }
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
浅析我对 String、StringBuilder、StringBuffer 的理解
使用IDEA搭建SSM框架的详细教程(spring + springMVC +MyBatis)
Springboot整合freemarker 404问题解决方案
引入mybatis-plus报 Invalid bound statement错误问题的解决方法
网友评论