Skip to content

Instantly share code, notes, and snippets.

@oxavibes
Created September 11, 2023 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oxavibes/ee42b7da34e2ea94b8b172e690a88459 to your computer and use it in GitHub Desktop.
Save oxavibes/ee42b7da34e2ea94b8b172e690a88459 to your computer and use it in GitHub Desktop.
Download file via js
async function downloadPDF() {
if (props.attachment) {
try {
// Extract the filename from the attachment URL.
const filename = props.attachment.substring(props.attachment.lastIndexOf('/') + 1)
// Send a GET request to the PDF URL.
const response = await fetch(props.attachment)
if (!response.ok)
throw new Error(`HTTP error! Status: ${response.status}`)
const blob = await response.blob()
// Create a temporary URL for the blob.
const url = window.URL.createObjectURL(blob)
// Create an anchor element to trigger the download.
const a = document.createElement('a')
a.href = url
a.download = filename // Use the extracted filename.
// Trigger a click event to start the download.
a.click()
// Clean up by revoking the temporary URL.
window.URL.revokeObjectURL(url)
}
catch (error) {
console.error('Error downloading PDF:', error)
// Handle the error, e.g., show an error message to the user.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment