UPDATE — XMLHTTP variant - It works but better solution below this post
This is what i came up to - please guys let me know if i can optimize stuff or if the approach i found is just plain stupid!
I used plain XMLHttpRequest, i couldn’t get it to work with blobs using Ionic’s http provider! This is the documentation i used to learn to use this kind of construct: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
downloadImage(url, name, file?, alertCtrl?) {
file = this.file;
alertCtrl = this.alertCtrl;
let alert = alertCtrl.create({
title: 'Download starting...',
subTitle: name+" will be downloaded.",
buttons: ['Cool, thanks!']
});
alert.present();
//REQUEST CREATION
let oReq = new XMLHttpRequest();
//SENDING REQUEST
oReq.open("GET", url, true);
oReq.responseType = "blob"; // blob pls
//IF DATA RECEIVED THEN WRITE FILE
oReq.onload = function(oEvent) {
//SAVE TEMP FILE IN APP FOLDER
file.writeFile(file.externalDataDirectory, 'tmp.jpg', oReq.response, { replace: true }).then( data => {
//COPY TMP FILE INTO USER GALLERY
(<any>window).cordova.plugins.imagesaver.saveImageToGallery(file.externalDataDirectory+'tmp.jpg', onSaveImageSuccess, onSaveImageError);
//ON SUCCESS
function onSaveImageSuccess(){
let alert = alertCtrl.create({
title: 'Image saved!',
subTitle: 'The picture \"'+name+'\" has been saved in your phone gallery.',
buttons: ['Cool, thanks!']
});
alert.present();
}
//ON FAIL
function onSaveImageError(error) {
let alert = this.alertCtrl.create({
title: 'There was a problem downloading your image :(.',
subTitle: 'For some reason we couldn\'t save the picture in your gallery. Please try again!',
buttons: ['Damn!']
});
alert.present();
}
});
};
oReq.send();//this is useless right?
}
It works. The downloaded picture is moved into the gallery exactly like any downloaded image from your browser.
Now i’m trying to add tracking for the download because as of now the user has no clue if the download is actually working apart from the alerts at start and finish. From the doc page i linked early looks like i can use this:
// progress on transfers from the server to the client (downloads)
function updateProgress (oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total * 100;
// ...
} else {
// Unable to compute progress information since the total size is unknown
}
}
I’ll try to implement something similar but if you guys have some examples i’d gladly appreciate it! Thank you for your help guys, love ya