I am trying to download a file using JS, without linking to it in HTML and without creating temporary DOM elements like some of the old tricks suggest.
I found this snippet that almost works, it lets me download the file but it assigns it a generated name. Adding the Content-Disposition
option to header works for the fetch
part but it is disregarded later with blob
.
const options = {
headers: {
"Content-Disposition": 'attachment; filename="report.pdf"'
}
}
function downloadPdf() {
fetch("./report.pdf", options)
.then(res => res.blob())
.then(blob => {
let file = window.URL.createObjectURL(blob);
window.location.assign(file);
});
}
downloadButton.addEventListener("click", downloadPdf, false);
How can I pass the name of the file from Content-Disposition
header to the created blob?