Created
May 30, 2015 17:28
-
-
Save code-for-coffee/11d4afd83fa8425d9bd0 to your computer and use it in GitHub Desktop.
Using FileReader to convert a file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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