将base64解码为字节

将base64解码为字节

本文介绍了InvalidCharacterError:字符串包含无效字符,同时使用atob()将base64解码为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用atob()函数将base64字符串转换为字节数组.

I am converting a base64 String to byte array using atob() function.

我从下面的代码中获取base64String:

I get the base64String from below code:

var dataURL = $("#graph-panel .canvasjs-chart-canvas").get(0).toDataURL();

dataURL的内容如下:

Contents of dataURL is as follows:

我认为上述base64字符串不是完整的字符串.无论在控制台中打印了什么字符串,我都将其粘贴在上面.

The above base64 String is not a complete string I think. Whatever the string that got printed in the console I have pasted it above.

我正在将此base64字符串传递给以下函数:

I am passing this base64 String to the following function:

var bytes = b64DecodeUnicode(dataUrl);

function b64DecodeUnicode(str) {
console.log(str);
// Going backwards: from bytestream, to percent-encoding, to original string.
return decodeURIComponent(atob(str).split('').map(function(c) {
    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));

}

在执行上述代码时,出现以下错误:

While executing the above code I am getting the following errror:

以下是完整的Base64字符串:

推荐答案

好像您正在尝试使用atob()函数转换DataURL,但是您错过了一步.

Looks like you're trying to convert a DataURL using the atob() function, but you have missed a step.

DataURL包含有关媒体类型和编码的信息,如下所示:

The DataURL contains information about the media type and the encoding like so:

data:[<mediatype>][;base64],<data>

您可以尝试通过使用base64,

尝试一下:

data = str.split('base64,')[1];

参考: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs

这篇关于InvalidCharacterError:字符串包含无效字符,同时使用atob()将base64解码为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 14:10