Hello
I have a requirement where I have doc/pdf/xls/jpeg/png files saved in the backend. I have a backend path where the files are retrieved as a blob.
Now, as a requirement I want to download the file to the local storage of the device. As a usecase I want that the downloaded file can be viewed using native apps like adobe, ms office etc. The same usecase as downloading an attachment and viewing from gmail.
I cannot find a good alternative for this in native mode. The capacitor Filesystem seem to only save in application specific storage and not accessible outside it, eg: from gallery
I did find a few posts which suggest using ‘@awesome-cordova-plugins/http/ngx’. This looks to be an Angular specific package. I am using Ionic React.
I have this code working for web mode
let url = window.URL.createObjectURL(res.data);
let a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = res.filename;
a.click();
window.URL.revokeObjectURL(url);
Any help is greatly appreciated.
Regards
1 Like
Hello,
Did you find a solution for this problem?
I have the same issue and I cannot find any clear answer.
Take a look at downloadFile(…).
Thank you.
This solution worked for me.
.....
if (Capacitor.isNativePlatform()) {
const base64 = await convertBlobToBase64(blob)
const saveFile = await Filesystem.writeFile({
path: filename,
data: base64,
directory: Directory.Data
})
const path = saveFile.uri
FileOpener.open({
filePath: path,
contentType: blob.type
})
.then(() => {console.log('File is opened')})
.catch((error) => {console.log(error)})
} else {
const href = window.URL.createObjectURL(blob)
downloadFile(href, filename);
}
....
export const convertBlobToBase64 = (blob) => new Promise((resolve, reject) => {
const reader = new FileReader
reader.onerror = reject
reader.onload = () => {
resolve(reader.result)
}
reader.readAsDataURL(blob)
})
export function downloadFile(href, filename) {
const link = document.createElement("a");
link.style.display = "none";
link.href = href;
link.download = filename;
document.body.appendChild(link);
link.click();
setTimeout(() => {
URL.revokeObjectURL(link.href);
link.parentNode.removeChild(link);
}, 0);
}
1 Like