I am working on an application in ionic framework and I need to send the following object by $http
by post method.
$scope.project = {
name: '',
description:'',
location: '',
imgs: {},
video: ''
};
I have no problem with the name, description or location. The problem arises when wanting to store images in base64 within "imgs".
To be able to convert the images I use the following function:
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
}
And this is how I call her:
allImages
is an array with the paths of the images.
if($scope.allImages.length>0){
for (var i = 0; i < $scope.allImages.length; i++) {
toDataUrl($scope.allImages[i], function(base64File){
alert(base64File);
//Guardar valor en base64 en el objeto.
$scope.project.imgs[i]=base64File;
});
}
}
imprimeObjeto($scope.project.imgs);
But when executing my code what happens is that, first the impression that I do until the end is shown: imprimeObjeto($scope.project.imgs);
and it shows me everything empty, then it shows the alert with the correct code in base64 converted to the 'toDataUrl' function, I can see all the image code in base64 , but this value is not saved in the array, or only saves the value of the last selected image.
What I need is to save the base64 code inside the imgs
object something like this:
$scope.project = {
name: '',
description:'',
location: '',
imgs: {
0 : 'codigoBase64blabla.....',
1 : 'codigoBase64blaasdq....',
2 : 'codigoBase64blablalbla.',
3 : 'codigoBase64blabla.....',
4 : 'codigoBase64blabla.....'
},
video: ''
};
But for some reason, the code in base64 is generated but not stored in the array.
I think it takes too long to convert the images and that makes it skip lines of code. Is there a way to first save the images in base64 inside the object and not print the end first?
Even I am very new in angular, can this be done with promises?