-
-
Save oxavibes/ee42b7da34e2ea94b8b172e690a88459 to your computer and use it in GitHub Desktop.
Download file via js
This file contains 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
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