我试图强制浏览器下载 PDF 或图像,而不是打开新选项卡。我使用谷歌浏览器。但是,当我测试以下链接下的示例时,它有效: https: //www.w3schools.com/tags/tryit.asp ?filename=tryhtml5_a_download
但它对我不起作用(见下文)。除 PDF 和图像外,其他文件类型仍会触发下载。`const url = 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)
}`
Run Code Online (Sandbox Code Playgroud)
那么,我在这里做错了什么?
问题可能是 href URL 与您的来源不同,请注意,它download仅适用于:
好吧...现在的解决方案是先获取文件,然后将其转换为 BLOB 文件,如下例所示:
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
*/
});
Run Code Online (Sandbox Code Playgroud)
注意: 如果 Access-Control-Allow-Origin 标头响应等于*,我们可以从该 URL/源的任何源获取响应,但我们不能使用 download 属性,因为该hrefURL 与当前的 URL 不同起源,在这种情况下,行为是不同的。
例如:
"https://blahblah.com" Response Header: Access-Control-Allow-Origin = *
Run Code Online (Sandbox Code Playgroud)
当前的 url/origin 是 = http://test.test.org
fetch("https://blahblah.com") //pass
<a download href="https://blahblah.com/file.pdf" /> //failed! (actually the download attribute does not work here)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6773 次 |
| 最近记录: |