问题提出:
自己在做一个小网站充当练手,但是前端图片经过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();
}
希望与广大网友互动??
点此进行留言吧!