commission--yt-commit
This commit is contained in:
58
utils/decodebase64.js
Normal file
58
utils/decodebase64.js
Normal file
@ -0,0 +1,58 @@
|
||||
function decodeBase64(base64Str) {
|
||||
try {
|
||||
// 第一步:先 URL 解码(解决 %2B、%3D 等问题)
|
||||
const urlDecoded = decodeURIComponent(base64Str);
|
||||
|
||||
// 第二步:处理 Base64 字符(替换 URL 安全字符)
|
||||
let safeBase64 = urlDecoded
|
||||
.replace(/-/g, "+")
|
||||
.replace(/_/g, "/")
|
||||
.replace(/\s/g, "");
|
||||
|
||||
// 补全等号
|
||||
const pad = safeBase64.length % 4;
|
||||
safeBase64 = safeBase64.padEnd(
|
||||
safeBase64.length + (pad ? 4 - pad : 0),
|
||||
"="
|
||||
);
|
||||
|
||||
// 第三步:使用微信小程序提供的 base64 解码函数
|
||||
const arrayBuffer = wx.base64ToArrayBuffer(safeBase64);
|
||||
const bytes = new Uint8Array(arrayBuffer);
|
||||
|
||||
// 第四步:手动 UTF-8 解码
|
||||
let utf8Str = "";
|
||||
let i = 0;
|
||||
while (i < bytes.length) {
|
||||
const byte = bytes[i];
|
||||
if (byte < 0x80) {
|
||||
utf8Str += String.fromCharCode(byte);
|
||||
i++;
|
||||
} else if (byte < 0xe0) {
|
||||
utf8Str += String.fromCharCode(
|
||||
((byte & 0x1f) << 6) | (bytes[i + 1] & 0x3f)
|
||||
);
|
||||
i += 2;
|
||||
} else if (byte < 0xf0) {
|
||||
utf8Str += String.fromCharCode(
|
||||
((byte & 0x0f) << 12) |
|
||||
((bytes[i + 1] & 0x3f) << 6) |
|
||||
(bytes[i + 2] & 0x3f)
|
||||
);
|
||||
i += 3;
|
||||
} else {
|
||||
// 四字节字符跳过
|
||||
i += 4;
|
||||
}
|
||||
}
|
||||
|
||||
return utf8Str;
|
||||
} catch (e) {
|
||||
console.error("Base64解码失败:", e);
|
||||
return "<p>内容解析错误</p>";
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
decodeBase64
|
||||
};
|
Reference in New Issue
Block a user