Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

javascript - 如何在JavaScript中将字符串编码为Base64?(How can you encode a string to Base64 in JavaScript?)

I have a PHP script that can encode a PNG image to a Base64 string.

(我有一个PHP脚本,可以将PNG图像编码为Base64字符串。)

I'd like to do the same thing using JavaScript.

(我想使用JavaScript做同样的事情。)

I know how to open files, but I'm not sure how to do the encoding.

(我知道如何打开文件,但不确定如何进行编码。)

I'm not used to working with binary data.

(我不习惯使用二进制数据。)

  ask by username translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use btoa() and atob() to convert to and from base64 encoding.

(您可以使用btoa()atob()在base64编码之间进行转换。)

There appears to be some confusion in the comments regarding what these functions accept/return, so…

(关于这些功能接受/返回的内容,评论中似乎有些混乱,因此……)

  • btoa() accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can't be represented in 8 bits, it will probably break .

    (btoa()接受一个“字符串”,其中每个字符代表一个8位字节–如果传递的字符串包含无法以8位表示的字符,则它可能会中断 。)

    This isn't a problem if you're actually treating the string as a byte array, but if you're trying to do something else then you'll have to encode it first.

    (如果您实际上将字符串视为字节数组,那么这不是问题,但是如果您尝试执行其他操作,则必须先对其进行编码。)

  • atob() returns a “string” where each character represents an 8-bit byte – that is, its value will be between 0 and 0xff .

    (atob()返回一个“字符串”,其中每个字符代表一个8位字节-也就是说,其值将在00xff之间。)

    This does not mean it's ASCII – presumably if you're using this function at all, you expect to be working with binary data and not text.

    (这并不意味着它是ASCII -大概,如果您使用此功能在所有的,你还指望用二进制数据,而不是文字来工作。)

See also: (也可以看看:)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...