A Pen by Ashish Vishwakarma on CodePen.
Created
April 10, 2016 09:46
-
-
Save AshV/d74b36916868ee17342ce5d8f6389b7c to your computer and use it in GitHub Desktop.
Convert File to base64
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
<input type="file" id="files" name="files" /> | |
<br/> | |
<textarea id="base64" rows="5"></textarea> |
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
// Check for the File API support. | |
if (window.File && window.FileReader && window.FileList && window.Blob) { | |
document.getElementById('files').addEventListener('change', handleFileSelect, false); | |
} else { | |
alert('The File APIs are not fully supported in this browser.'); | |
} | |
function handleFileSelect(evt) { | |
var f = evt.target.files[0]; // FileList object | |
var reader = new FileReader(); | |
// Closure to capture the file information. | |
reader.onload = (function(theFile) { | |
return function(e) { | |
var binaryData = e.target.result; | |
//Converting Binary Data to base 64 | |
var base64String = window.btoa(binaryData); | |
//showing file converted to base64 | |
document.getElementById('base64').value = base64String; | |
alert('File converted to base64 successfuly!\nCheck in Textarea'); | |
}; | |
})(f); | |
// Read in the image file as a data URL. | |
reader.readAsBinaryString(f); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment