Skip to content

Instantly share code, notes, and snippets.

@dannysmc95
Last active February 18, 2024 03:02
Show Gist options
  • Save dannysmc95/f8c922e486299efef787b062585da5a6 to your computer and use it in GitHub Desktop.
Save dannysmc95/f8c922e486299efef787b062585da5a6 to your computer and use it in GitHub Desktop.
Download a file with pure Capacitor FileSystem and the Fetch API.
const downloadFile = async (uri, path, folder) => {
return new Promise(async (resolve, reject) => {
try {
const file_request = await fetch(uri, {
method: 'GET',
credentials: 'include',
mode: 'cors',
});
const file_blob = await file_request.blob();
const reader = new FileReader();
reader.readAsDataURL(file_blob);
reader.onloadend = async () => {
await Capacitor.Plugins.Filesystem.writeFile({
path: path,
data: reader.result,
directory: folder,
recursive: true,
});
resolve(true);
}
} catch(err) {
reject(err);
}
});
}
// Use it like
(async () => {
await downloadFile('https://example.com/hello.zip', '/hello.zip', 'DATA');
})();
@dannysmc95
Copy link
Author

Thank this was really helpful
edit: although FileSystem should be Filesystem it took me a while to figure it out

I just fixed that, my bad, (I know I am like 7 months late, my bad - never saw this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment