Skip to content

Instantly share code, notes, and snippets.

@lazerg
Created February 23, 2022 04:52
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lazerg/c975ab542499a992e866d0975a32411c to your computer and use it in GitHub Desktop.
Save lazerg/c975ab542499a992e866d0975a32411c to your computer and use it in GitHub Desktop.
Promise based file to base64 conversion
/**
* Converts file to base64
*
* @param {File} file
* @return {Promise<String>}
*/
export default file => {
return new Promise(resolve => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
})
}
@lazerg
Copy link
Author

lazerg commented Feb 23, 2022

Approximately usage:

import file_to_base64 from "@/helpers/file_to_base64";

/**
 * Event listener for input
 *
 * @param {File} file
 */
const onInputChange = async file => {
    const content = await file_to_base64(file);

    // ...
}

@adiasrim
Copy link

A very helpful helper for handling files. Thank you, what we needed.

@behzodjon
Copy link

Bravo! A very Useful hint!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment