Skip to content

Instantly share code, notes, and snippets.

@code-for-coffee
Created May 30, 2015 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-for-coffee/11d4afd83fa8425d9bd0 to your computer and use it in GitHub Desktop.
Save code-for-coffee/11d4afd83fa8425d9bd0 to your computer and use it in GitHub Desktop.
Using FileReader to convert a file
/**
* convertToBase64
* @param binaryData: Input data from an <input type="file">
*/
function convertToBase64(binaryData) {
// use a FileReader
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader
var reader = new FileReader();
reader.onload = function (event) {
// try to read whatever file has been 'readAsDataURL'
try {
// event target result is our base64 encoded type
// this is whatever file has been reader during 'readAsDataURL'
console.log(event.target.result);
return(event.target.result);
// catch an error if one occurs...
} catch (ex) {
// output a warning in the DevTools console
throw new Error("Couldn't convert file: " + ex);
}
}
// read the file argument
reader.readAsDataURL(binaryData);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment