Created
August 16, 2024 00:07
Function for donwload file in js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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