-
Notifications
You must be signed in to change notification settings - Fork 408
/
Copy pathbase64.js
28 lines (26 loc) · 907 Bytes
/
base64.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// @flow
/**
* Encode the ArrayBuffer{,View} bytes into a base64 data url.
*/
export async function bytesToBase64DataUrl(
bytes: $ArrayBufferView | ArrayBuffer,
type: string = 'application/octet-stream'
): Promise<string> {
return new Promise((resolve, reject) => {
const reader = Object.assign(new FileReader(), {
onload: () => resolve((reader.result: any)),
onerror: () => reject(reader.error),
});
reader.readAsDataURL(new Blob([bytes], { type }));
});
}
/**
* Decode the encoded base64 data url into bytes array.
*/
export async function dataUrlToBytes(dataUrl: string): Promise<ArrayBuffer> {
const res = await fetch(dataUrl);
return res.arrayBuffer();
}