|
| 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