Skip to content

Instantly share code, notes, and snippets.

@otnansirk
Created August 16, 2024 00:07
Show Gist options
  • Save otnansirk/3d068e0155a1d1bf60833dcda59a61d9 to your computer and use it in GitHub Desktop.
Save otnansirk/3d068e0155a1d1bf60833dcda59a61d9 to your computer and use it in GitHub Desktop.
Function for donwload file in js
export const downloadHandler = async (uri) => {
try {
const response = await fetch(uri, {
mode: 'cors',
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
const filename = uri.substring(uri.lastIndexOf('/') + 1);
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
// Clean up
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
} catch (error) {
console.error('Failed to download file:', error);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment