如何在 JavaScript 中将字符串编码为 Base64? [英] How can you encode a string to Base64 in JavaScript?
问题描述
我有一个 PHP 脚本,可以将 PNG 图像编码为 Base64 字符串.
I have a PHP script that can encode a PNG image to a Base64 string.
我想用 JavaScript 做同样的事情.我知道如何打开文件,但我不确定如何进行编码.我不习惯使用二进制数据.
I'd like to do the same thing using 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.
推荐答案
您可以使用 btoa()
和 atob()
来转换 base64 编码.
You can use btoa()
and atob()
to convert to and from base64 encoding.
关于这些函数接受/返回什么的评论似乎有些混乱,所以......
There appears to be some confusion in the comments regarding what these functions accept/return, so…
btoa()
接受一个字符串",其中每个字符代表一个 8 位字节——如果你传递的字符串包含不能用 8 位表示的字符,它可能会崩溃.这不是问题如果您实际上将字符串视为字节数组,但如果您尝试做其他事情,则必须先对其进行编码.
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. 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()
返回一个字符串",其中每个字符代表一个 8 位字节——也就是说,它的值将介于 0
和 之间>0xff
.这并不不是意味着它是 ASCII - 大概如果你正在使用这个函数,你希望使用二进制数据而不是文本.
atob()
returns a "string" where each character represents an 8-bit byte – that is, its value will be between 0
and 0xff
. 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.
这里的大多数评论都过时了.您可能可以同时使用 btoa()
和 atob()
,除非您支持非常过时的浏览器.
Most comments here are outdated. You can probably use both btoa()
and atob()
, unless you support really outdated browsers.
检查这里:
这篇关于如何在 JavaScript 中将字符串编码为 Base64?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!