Reputation: 458
So I have a Spring Boot + Vue.js application server running in the network. I also have a Cordova InAppBrowser Andorid app that shows the frontend.
I have to be able to use the application both from a real browser running on a machine and from the Cordova application. It works well so far.
But: When I want to download a json formatted text file or any other file from the server inside the Cordova app, it does not work. I have read a lot of articles, and other questions on this topic, but most of them were simply outdated.
So is there a way to achieve this? Currently my code that works from browser (we use Chrome) looks something like this:
api({
url: url,
method: 'GET',
responseType: 'blob',
}).then((response) => {
const blob = new Blob([response.data], {type: response.data.type})
const url = window.URL.createObjectURL(blob)
let fileName = extractFilename(response)
const link = document.createElement('a')
link.href = url
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
link.remove()
window.URL.revokeObjectURL(url)
})
Upvotes: 0
Views: 1564
Reputation: 3452
The reason is because downloading file required File system access, which is stricter in Mobile app than desktop. So simple download attribute is not working.
You need to install cordova-plugin-file
: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/
You can follow the tutorial there. Below is my example code if it helps:
saveBlobToSystem(filename, blob) {
// define the folder you want to save first, for example this is download folder in Android
let folderpath = "file:///storage/emulated/0/download/";
let vm = this;
const onError = function(msg) {
console.log("Error saving File to System");
};
window.resolveLocalFileSystemURL(folderpath, function(dir) {
console.log("Access to the directory granted succesfully");
dir.getFile(filename, { create: true }, function(file) {
console.log("File created succesfully.");
file.createWriter(function(fileWriter) {
console.log("Writing content to file");
fileWriter.write(blob);
console.log("Successfully write file to system");
}, onError);
}, onError);
}, onError);
}
However, this cordova plugins may not work on web version, so i think you still need to keep your old code. You can write a simple js function to detect user platform ( web or android app ) and run the corresponding function.
Upvotes: 0