I have a cordova - ionic application. I want to download a file from webservice and the file may be any type(JPG,PDG,DOCX etc). I cannot download the file from direct URL. So the app is taking byte array of the file from Webservice.
Anybody know how to download the file in Mobile from the Byte Array. Please help me.
you can use the cordova-plugin-file and the cordova-plugin-file-opener2 plugin.
https://github.com/apache/cordova-plugin-file
https://github.com/pwlin/cordova-plugin-file-opener2
in function with the webservice your code should look like that:
var bytes = new Uint8Array(data.d);
app.writePDFToFile(fileName.split(fileName.split, bytes);
and here is teh function forcing the download:
writePDFToFile: function (fileName, data) {
try {
window.resolveLocalFileSystemURL(cordova.file.externalApplicationStorageDirectory, function (directoryEntry) {
directoryEntry.getFile(fileName, { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function (e) {
//window.open(cordova.file.externalApplicationStorageDirectory + fileName, '_system', 'location=yes');
cordova.plugins.fileOpener2.open(cordova.file.externalApplicationStorageDirectory + fileName, 'application/pdf',
{
error: function (e) {
console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
},
success: function () {
console.log('file opened successfully');
}
}
);
};
fileWriter.onerror = function (e) {
alert(e);
};
var blob = new Blob([data], { type: 'application/pdf' });
fileWriter.write(blob);
}, function onerror(e) {
alert(e);
});
}, function onerror(e) {
alert(e);
});
}, function onerror(e) {
alert(e);
});
} catch (e) {
alert(e);
}
},
Hope this will help!