uniapp 微信小程序使用TextEncoder,arrayBufferToBase64
有一些小程序会在真机报错TextEncoder main.js 第一行就加,不要放在后面
js
// main.js 第一行就加,不要放在后面
if (typeof TextEncoder === 'undefined') {
global.TextEncoder = class TextEncoder {
/**
* 将字符串转为UTF-8编码的Uint8Array
* 兼容ASCII、中文、emoji等所有Unicode字符
*/
encode(str) {
const arr = [];
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
// 处理单字节ASCII
if (code < 0x80) {
arr.push(code);
}
// 处理双字节字符
else if (code < 0x800) {
arr.push(0xc0 | (code >> 6), 0x80 | (code & 0x3f));
}
// 处理三字节/emoji等字符
else if (code < 0xd800 || code >= 0xe000) {
arr.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 0x3f), 0x80 | (code & 0x3f));
}
// 处理四字节代理对字符
else {
i++;
const nextCode = str.charCodeAt(i);
const fullCode = 0x10000 + (((code & 0x3ff) << 10) | (nextCode & 0x3ff));
arr.push(
0xf0 | (fullCode >> 18),
0x80 | ((fullCode >> 12) & 0x3f),
0x80 | ((fullCode >> 6) & 0x3f),
0x80 | (fullCode & 0x3f)
);
}
}
return new Uint8Array(arr);
}
};
}
输出base64 arrayBufferToBase64
js
const encoder = new TextEncoder();
str = encoder.encode(str).buffer;
let output = uni.arrayBufferToBase64(str)
console.log(output,'output'); 输出的