1 import { base64StringToUint8Array, uint8ArrayToString } from './encoding';
4 * Convert file to encoded base 64 string
6 export const toBase64 = async (file: Blob, isValid: (file: Blob) => boolean = () => true) => {
7 if (file && !isValid(file)) {
8 throw new Error('Invalid file format');
10 return new Promise<string>((resolve, reject) => {
11 const reader = new FileReader();
12 reader.onload = ({ target }) => {
13 if (!target?.result) {
14 return reject(new Error('Invalid file'));
16 resolve(target.result as string);
18 reader.onerror = reject;
19 reader.onabort = reject;
20 reader.readAsDataURL(file);
25 * Read the content of a blob and returns its value as a buffer
27 export const readFileAsBuffer = (file: File) => {
28 return new Promise<ArrayBuffer>((resolve, reject) => {
29 const reader = new FileReader();
30 reader.onload = ({ target }) => {
31 if (!target?.result) {
32 return reject(new Error('Invalid file'));
34 resolve(target.result as ArrayBuffer);
36 reader.onerror = reject;
37 reader.onabort = reject;
38 reader.readAsArrayBuffer(file);
43 * Read the content of a blob and returns its value as a text string
45 export const readFileAsString = (file: File, encoding?: string) => {
46 return new Promise<string>((resolve, reject) => {
47 const reader = new FileReader();
48 reader.onload = ({ target }) => {
49 if (!target?.result) {
50 return reject(new Error('Invalid file'));
52 resolve(target.result as string);
54 reader.onerror = reject;
55 reader.onabort = reject;
56 reader.readAsText(file, encoding);
61 * Read the content of a blob and returns its value as a binary string.
62 * Not using readAsBinaryString because it's deprecated.
64 export const readFileAsBinaryString = async (file: File) => {
65 const arrayBuffer = await readFileAsBuffer(file);
66 // eslint-disable-next-line new-cap
67 return uint8ArrayToString(new Uint8Array(arrayBuffer));
71 * Convert a blob url to the matching blob
72 * @link https://stackoverflow.com/a/42508185
74 export const blobURLtoBlob = (url: string) => {
75 return new Promise((resolve, reject) => {
76 const xhr = new XMLHttpRequest();
78 xhr.responseType = 'blob';
81 if (xhr.status === 200) {
82 return resolve(xhr.response);
91 * Read the base64 portion of a data url.
93 export const readDataUrl = (url = '') => {
94 const error = 'The given url is not a data url.';
96 if (url.substring(0, 5) !== 'data:') {
97 throw new Error(error);
100 const [, base64] = url.split(',');
102 throw new Error(error);
105 return base64StringToUint8Array(base64);
109 * Split a filename into [name, extension]
111 export const splitExtension = (filename = '') => {
112 const endIdx = filename.lastIndexOf('.');
114 return [filename, ''];
116 return [filename.slice(0, endIdx), filename.slice(endIdx + 1)];