Last active
          July 14, 2023 16:11 
        
      - 
      
- 
        Save matinrco/563dfa706a338c0e6be60378541bc1b7 to your computer and use it in GitHub Desktop. 
    Convert any file to base64 in javascript 
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | 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