当前位置: 移动技术网 > IT编程>开发语言>Java > Java Base64解码错误及解决方法

Java Base64解码错误及解决方法

2019年07月19日  | 移动技术网IT编程  | 我要评论

饲妖,中国美院教务网,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();
  }

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网