温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java Base64解码错误怎么办

发布时间:2021-06-26 11:41:29 来源:亿速云 阅读:628 作者:小新 栏目:编程语言

这篇文章将为大家详细讲解有关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();

Java Base64解码错误怎么办

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解码错误怎么办”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI