js对中文进行base64编码和解码操作,解决中文乱码问题

我使用github api的接口获取文件内容,然后使用atob进行解码,但是发现:乱码.......糟心啊

所以就有了我封装的方法:

export const encode64 = (str) => {
  // 首先,我们使用 encodeURIComponent 来获得百分比编码的UTF-8,然后我们将百分比编码转换为原始字节,最后存储到btoa里面
  return btoa(
    encodeURIComponent(str).replace(
      /%([0-9A-F]{2})/g,
      function toSolidBytes(_, p1) {
        return String.fromCharCode(Number("0x" + p1));
      }
    )
  );
};

export const decode64 = (str) => {
  // 过程:从字节流到百分比编码,再到原始字符串
  return decodeURIComponent(
    atob(str)
      .split("")
      .map(function (c) {
        return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
      })
      .join("")
  );
};

然后调用:

再看结果:完美

猜你喜欢

转载自blog.csdn.net/weixin_44786530/article/details/132629882