Image convert to Base64
Exactly what you need:) You can choose callback version or Promise version. Note that promises will work in IE only with Promise polyfill lib.You can put this code once on a page, and this function will appear in all your files.
The loadend event is fired when progress has stopped on the loading of a resource (e.g. after "error", "abort", or "load" have been dispatched)
Callback version
File.prototype.convertToBase64 = function(callback){
var reader = new FileReader();
reader.onloadend = function (e) {
callback(e.target.result, e.target.error);
};
reader.readAsDataURL(this);
};
$("#asd").on('change',function(){
var selectedFile = this.files[0];
selectedFile.convertToBase64(function(base64){
alert(base64);
})
});
Promise version
File.prototype.convertToBase64 = function(){
return new Promise(function(resolve, reject) {
var reader = new FileReader();
reader.onloadend = function (e) {
resolve({
fileName: this.name,
result: e.target.result,
error: e.target.error
});
};
reader.readAsDataURL(this);
}.bind(this));
};
FileList.prototype.convertAllToBase64 = function(regexp){
// empty regexp if not set
regexp = regexp || /.*/;
//making array from FileList
var filesArray = Array.prototype.slice.call(this);
var base64PromisesArray = filesArray.
filter(function(file){
return (regexp).test(file.name)
}).map(function(file){
return file.convertToBase64();
});
return Promise.all(base64PromisesArray);
};
$("#asd").on('change',function(){
//for one file
var selectedFile = this.files[0];
selectedFile.convertToBase64().
then(function(obj){
alert(obj.result);
});
});
//for all files that have file extention png, jpeg, jpg, gif
this.files.convertAllToBase64(/\.(png|jpeg|jpg|gif)$/i).then(function(objArray){
objArray.forEach(function(obj, i){
console.log("result[" + obj.fileName + "][" + i + "] = " + obj.result);
});
});
})
html
<input type="file" id="asd" multiple/>
<input type="file" onchange="getBaseUrl()">
function getBaseUrl () {
var file = document.querySelector('input[type=file]')['files'][0];
var reader = new FileReader();
var baseString;
reader.onloadend = function () {
baseString = reader.result;
console.log(baseString);
};
reader.readAsDataURL(file);
}
function readFile() {
if (!this.files || !this.files[0]) return;
const FR = new FileReader();
FR.addEventListener("load", function(evt) {
document.querySelector("#img").src = evt.target.result;
document.querySelector("#b64").textContent = evt.target.result;
});
FR.readAsDataURL(this.files[0]);
}
document.querySelector("#inp").addEventListener("change", readFile);
<input id="inp" type="file">
<p id="b64"></p>
<img id="img" height="150">
(P.S: A base64 encoded image (String) 4/3 the size of the original image data)
Check this answer for multiple images upload.
Browser support: http://caniuse.com/#search=file%20api
More info here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader