HarmonyOS 鸿蒙Next base64解码报错
HarmonyOS 鸿蒙Next base64解码报错
let codeResult: TCommonResult<ImgCodeResult> = JSON.parse(data);
let base64Code: string = codeResult.data!.validCode;
PiccLog.debug("base64Code = " + base64Code)
let base64Utils = new util.Base64Helper();
let uint8Array: Uint8Array = base64Utils.decodeSync(base64Code, util.Type.BASIC);
// let uint8Array:Uint8Array = base64Utils.decodeSync(base64Code, util.Type.MIME);
使用base64解码报错,报错信息如下: Error name:Error Error message:The input string contains unsupported characters Error code:-1 Stacktrace: at decodeSync (/usr1/hmos_for_system/src/increment/sourcecode/out/generic_generic_arm_64only/hisi_all_phone_standard/obj/commonlibrary/ets_utils/js_util_module/util/util_js.js:63:63) 后台返回的图片为base64转码的字符串,需要进行解码。
根据报错信息提示:输入字符串包含不支持的字符,可以先把字符串处理一下,参考以下demo:
// 字符串转成字节流
function stringToUint8Array(str: string) {
return new Uint8Array(buffer.from(str, 'utf-8').buffer);
}
// 字节流转成可理解的字符串
function uint8ArrayToString(array: Uint8Array): string {
// 将UTF-8编码转换成Unicode编码
let out: string = "";
let index: number = 0;
let len: number = array.length;
while (index < len) {
let character = array[index++];
switch (character >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
out += String.fromCharCode(character);
break;
case 12:
case 13:
out += String.fromCharCode(((character & 0x1F) << 6) | (array[index++] & 0x3F));
break;
case 14:
out += String.fromCharCode(((character & 0x0F) << 12) | ((array[index++] & 0x3F) << 6) | ((array[index++] & 0x3F) << 0));
break;
default:
break;
}
}
return out;
}
function doDecryption(encodeString: string) {
let base64_ = new util.Base64Helper();
let decodeArr: Uint8Array = base64_.decodeSync(encodeString);
let decodeStr = uint8ArrayToString(decodeArr);
log.info('doEncrypted, decodeArr: ' + decodeArr);
log.info('doEncrypted, decodeStr: ' + decodeStr);
}