javascript - convert file to base64 (web browser api)

JavaScript
[Edit]
+
0
-
0

JavaScript - convert File to Base64 (web browser API)

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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
const toBase64 = async (file) => { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = function() { var url = reader.result; if (url) { const index = url.indexOf('base64,'); if (index === -1) { reject('Base64 data is not available.'); } else { resolve(url.substring(index + 7)); } } else { reject('Base64 data is not available.'); } }; reader.onerror = function() { reject('Incorrect file object.'); }; reader.readAsDataURL(file); }); }; // Usage example (use it in async context): const file = ... const base64 = await toBase64(file); // <script> // async function handleChange(input) { // Hint: you can use async function here also. // var files = input.files; // if (files.length > 0) { // var file = files[0]; // const base64 = await toBase64(file); // ... // } // } // </script> // <input type="file" onchange="handleChange(this)" /> // See also: // // 1. https://dirask.com/snippets/JavaScript-convert-Blob-to-Base64-web-browser-API-pVN89p // 2. https://dirask.com/snippets/JavaScript-convert-base64-to-Blob-j8dYrj