如何将 ArrayBuffer 转换为 Base64 编码的字符串?
我需要一种有效的(读取本机)方法将 ArrayBuffer 转换为需要在多部分帖子上使用的 base64 字符串。
I need an efficient (read native) way to convert an ArrayBuffer
to a base64 string which needs to be used on a multipart post.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(21)
但是,非本机实现速度更快,例如 https://gist.github.com/958841
请参阅http://jsperf.com/encoding-xhr-image-data/6
jsPerf.com
现在是jsPerf.app
:https://jsperf.app/encoding-xhr-image-data/51更新基准:https ://jsben.ch/wnaZC
but, non-native implementations are faster e.g. https://gist.github.com/958841
see http://jsperf.com/encoding-xhr-image-data/6
jsPerf.com
isjsPerf.app
now: https://jsperf.app/encoding-xhr-image-data/51Updated benchmarks: https://jsben.ch/wnaZC
这对我来说效果很好:
在 ES6 中,语法稍微简单一些:
正如注释中指出的,当 ArrayBuffer 很大时,此方法可能会导致某些浏览器中出现运行时错误。无论如何,确切的大小限制取决于实现。
This works fine for me:
In ES6, the syntax is a little simpler:
As pointed out in the comments, this method may result in a runtime error in some browsers when the
ArrayBuffer
is large. The exact size limit is implementation dependent in any case.对于那些喜欢简短的人,这里有另一个使用 Array.reduce 的方法,它不会导致堆栈溢出:
For those who like it short, here's an other one using
Array.reduce
which will not cause stack overflow:OP 没有指定运行环境,但如果您使用 Node.JS,有一个非常简单的方法可以做到这一点。
根据 Node.JS 官方文档:
https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
另外,如果您例如,在 Angular 下运行时,
Buffer
类也将在浏览器环境中可用。The OP did not specify the Running Environment, but if you are using Node.JS there is a very simple way to do this.
According to the official Node.JS docs:
https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
Also, if you are running under Angular for example, the
Buffer
class will also be made available in a browser environment.还有另一种异步方式使用 Blob 和 FileReader。
我没有测试性能。但这是一种不同的思维方式。
There is another asynchronous way use Blob and FileReader.
I didn't test the performance. But it is a different way of thinking.
此示例使用内置 FileReader readDataURL() 转换为 Base64 编码。 数据 URL 是结构化的
数据:[][;base64],
,因此我们在逗号处拆分该 url,并仅返回 base64 编码的字符。或者作为承诺的实用程序:
This example uses the built-in FileReader readDataURL() to do the conversion to base64 encoding. Data URLs are structured
data:[<mediatype>][;base64],<data>
, so we split that url at the comma and return only the base64 encoded characters.Or as a promisified utility:
我用过这个并且为我工作。
I used this and works for me.
我对此的建议是不要使用本机
btoa
策略,因为它们无法正确编码所有ArrayBuffer
的…重写 DOM atob() 并btoa()
虽然我从未遇到过这个确切的错误,但我发现我尝试编码的许多 ArrayBuffer 编码不正确。
我要么使用 MDN 推荐,要么使用 gist。
My recommendation for this is to NOT use native
btoa
strategies—as they don't correctly encode allArrayBuffer
's…rewrite the DOMs atob() and btoa()
While I have never encountered this exact error, I have found that many of the
ArrayBuffer
's I have tried to encode have encoded incorrectly.I would either use MDN recommendation or gist.
下面是两个简单的函数,用于将 Uint8Array 转换为 Base64 字符串并再次转换回来
Below are 2 simple functions for converting Uint8Array to Base64 String and back again
在 Node.js 中(即不是浏览器):
In Node.js (i.e. not browser):
如果您同意添加库,base64-arraybuffer:
那么:
encode(buffer)
- 将 ArrayBuffer 编码为 Base64 字符串decode(str)
- 将 Base64 字符串解码为 ArrayBufferIf you're okay with adding a library, base64-arraybuffer:
then:
encode(buffer)
- Encodes ArrayBuffer into base64 stringdecode(str)
- Decodes base64 string to ArrayBuffer使用文件读取器的异步方法。
asynchronous method using file reader.
我使用
TextDecode
api 将其转换为普通文本,然后将其转换为 Base64i use
TextDecode
api to convert it to normal text and then convert it to Base64在浏览器中,使用
btoa
建议的解决方案似乎不错。但在 Node.js 中 btoa 已成为旧版
建议使用
buffer.toString(encoding)
,如
const myString = buffer.toString("base64")
In the Browser suggested solutions with
btoa
seem fine.But in Node.js btoa is Legacy
It is recommended to use
buffer.toString(encoding)
like
const myString = buffer.toString("base64")
这是一个 ES6 解决方案,比使用原生 btoa 函数快 3 倍,比 mobz 和 Emmanuel 提出的非原生解决方案快 1.25 倍。它的代码还尊重最新的良好编码实践,并使用更干净的二进制掩码以提高可读性:
Here is a ES6 solution that is 3 times faster than using the native btoa function and is 1.25 faster than the non-native solution proposed by mobz and Emmanuel. Its code also respect more recent good coding practices and uses way more clean binary masks for readability :
您可以使用 Array.prototype.slice 从 ArrayBuffer 派生普通数组。
使用 Array.prototype.map 等函数将字节转换为字符,并将它们连接在一起形成字符串。
此方法速度更快,因为其中没有运行字符串连接。
You can derive a normal array from the
ArrayBuffer
by usingArray.prototype.slice
.Use a function like
Array.prototype.map
to convert bytes in to characters andjoin
them together to forma string.This method is faster since there are no string concatenations running in it.
Uint8Array.prototype.toBase64
将很快实施浏览器!然后您将能够编写:
您还可以使用 这个 core-js 填充:
Uint8Array.prototype.toBase64
will soon be implemented on the browser!You will then be able to write:
You can also use this core-js polyfill:
使用
uint8-to-b64
包来做浏览器和 Node.js 中的编码/解码Use
uint8-to-b64
package to do encoding/decoding in browser and Node.js在我这边,使用 Chrome 导航器,我必须使用 DataView() 来读取 arrayBuffer
By my side, using Chrome navigator, I had to use DataView() to read an arrayBuffer
如果您使用 JSZip 从字符串中解压存档,这会更好
This is better, if you use JSZip for unpack archive from string