Skip to content

Instantly share code, notes, and snippets.

@matinrco
Last active July 14, 2023 16:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save matinrco/563dfa706a338c0e6be60378541bc1b7 to your computer and use it in GitHub Desktop.
Save matinrco/563dfa706a338c0e6be60378541bc1b7 to your computer and use it in GitHub Desktop.
Convert any file to base64 in javascript
var toBase64=function (file , callBack) {
file=file.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
callBack(file,reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
};
//usage with jquery
var fileEl=$('input[type=file]');
$(fileEl).on('change',function () {
toBase64(this,function (file,base64) {
console.log(file);
console.log(base64);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment