I am trying to force the browser to download when it es to a PDF or an image rather than opening a new tab. I use Google Chrome. However, when I test out the example under the following link, it works: .asp?filename=tryhtml5_a_download
But it does not work on mine (see following). Downloads still trigger for other file types but PDFs and images. `const urls = res.data
for (const idx in urls) {
// check if each url is working, if it is working, stop and download it
const link = document.createElement('a')
link.href = urls[idx]
link.target = '_blank'
link.download = tgt.name
link.rel = 'noopener noreferrer'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}`
So, what have I done wrong here?
I am trying to force the browser to download when it es to a PDF or an image rather than opening a new tab. I use Google Chrome. However, when I test out the example under the following link, it works: https://www.w3schools./tags/tryit.asp?filename=tryhtml5_a_download
But it does not work on mine (see following). Downloads still trigger for other file types but PDFs and images. `const urls = res.data
for (const idx in urls) {
// check if each url is working, if it is working, stop and download it
const link = document.createElement('a')
link.href = urls[idx]
link.target = '_blank'
link.download = tgt.name
link.rel = 'noopener noreferrer'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}`
So, what have I done wrong here?
Share Improve this question edited Mar 11, 2021 at 3:47 The epic face 007 6391 gold badge10 silver badges26 bronze badges asked Mar 11, 2021 at 1:11 Fangyi LiFangyi Li 511 silver badge8 bronze badges 1-
1
urls[idx]
is a URL... that URL is different from your current origin/hostname? – Parsa x86 Commented Mar 11, 2021 at 1:40
1 Answer
Reset to default 5Probably the problem is that the href URL is not the same as your origin, note that the download
only works for:
- same-origin URLs
- BLOB file
- data schema
well... now the solution is that to fetch the file first, then convert it to BLOB file, like the below example:
fetch("FILE URL!")
.then((response) => response.blob())
.then((blob) => {
/*
here you have access to your BLOB file and
only you have to put it in the href attribute
*/
});
NOTE: if the Access-Control-Allow-Origin header response has equal to *
, we can get the response from any origin from that URL/origin, but we can't use the download attribute with that because the href
URL is different from the current origin, In this case, behaviors are different.
e.g:
"https://blahblah." Response Header: Access-Control-Allow-Origin = *
the current url/origin is = http://test.test
fetch("https://blahblah.") //pass
<a download href="https://blahblah./file.pdf" /> //failed! (actually the download attribute does not work here)