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();
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();
}
希望與廣大網友互動??
點此進行留言吧!
總結
以上是生活随笔為你收集整理的java base64解码出错_Java Base64解码错误及解决方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java有装箱和拆箱吗_Java中装箱和
- 下一篇: Android获取最新发送短信的基本信息