Skip to content

Commit 8d4ff2c

Browse files
committed
add util function for creating base64 string from file in browser env
1 parent 338cda3 commit 8d4ff2c

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,4 @@ export * from './backup';
105105
export * from './cluster';
106106
export * from './connection';
107107
export * from './utils/uuid';
108+
export * from './utils/base64';

src/utils/base64.ts

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* This function converts a file blob into a base64 string so that it can be
3+
* sent to Weaviate and stored as a media field.
4+
*
5+
* This specific function is only applicable within the browser since it depends on
6+
* the FileReader API. It will throw an error if it is called in a Node environment.
7+
*
8+
* @param {Blob} blob The file blob to convert
9+
* @returns {string} The base64 string
10+
* @throws An error if the function is called outside of the browser
11+
*
12+
* @example
13+
* // Vanilla JS
14+
* const file = document.querySelector('input[type="file"]').files[0];
15+
* toBase64FromBlob(file).then((base64) => console.log(base64));
16+
*
17+
* // React
18+
* const [base64, setBase64] = useState('');
19+
* const onChange = (event) => toBase64FromBlob(event.target.files[0]).then(setBase64);
20+
*
21+
* // Submit
22+
* const onSubmit = (base64: string) => client.data
23+
* .creator()
24+
* .withClassName('MyClass')
25+
* .withProperties({ myMediaField: base64 })
26+
* .do();
27+
*
28+
*/
29+
export function toBase64FromBlob(blob: Blob): Promise<string> {
30+
if (typeof window === 'undefined') {
31+
throw new Error('This function is only available in the browser');
32+
}
33+
const reader = new FileReader();
34+
return new Promise((resolve, reject) => {
35+
reader.onload = resolve;
36+
reader.onerror = reject;
37+
reader.readAsDataURL(blob);
38+
}).then(() => {
39+
if (typeof reader.result !== 'string') {
40+
throw new Error(
41+
`Unexpected result when converting blob to base64 (result is not a string): ${reader.result}`
42+
);
43+
}
44+
return reader.result;
45+
});
46+
}

0 commit comments

Comments
 (0)