Vue/HTML/JS如何使用下载标签将文件下载到浏览器 [英] Vue/HTML/JS how to download a file to browser using the download tag
问题描述
此问题与提供的其他答案不同,因为我的问题集中在VUE上,并且VUE是否也有防止默认方法的方法.
This question is different from the other answer provided, because my question is focused on VUE and if VUE also has a way to prevent the default method.
这个问题更特定于HTML 5下载"以及:href的VUE绑定,以及为什么它不能阻止默认浏览器在新标签页中打开文件的行为.
This question is more specific to HTML 5 "download" along with VUE binding of the :href and why it doesn't work to prevent the default browser behavior of opening the file in a new tab.
预期的行为:将文件下载到浏览器
Expected behavior : Download the file to the browser
实际行为:在新标签页中打开文件
Actual behavior : Opens the file in a new tab
例外:在新选项卡中仅打开图像,pdf和浏览器兼容的文件,正常下载诸如.exe之类的其他文件-为什么这样做,可以在html中更改此行为吗?
Exception: Only images, pdf and browser compatible files are opened in a new tab, other files like .exe are downloaded as normal - Why is this, can this behavior be changed in html?
添加target ="_ blank"不能解决问题
Adding target="_blank" does not solve the problem
<a :href="downloadById(item.url)" download>Download</a>
单击上面的链接时,将在新的浏览器选项卡中打开文件,我需要防止这种默认行为,并在单击后强制进行下载. HTML 5标记下载"是用来解决此问题的,看来似乎行不通.
When the above link is clicked, the file is opened in a new browser tab, i need to prevent this default behavior and force a download upon click. The HTML 5 tag "download" is suppose to solve this problem doesn't seem to work.
Chrome最近不推荐使用跨域下载的下载标签表单. vue是否有修饰符来防止此默认设置?还有其他方法可以使用javascript或html下载文件吗?
Chrome has recently deprecated the download tag form working with cross domain downloads. Does vue have a modifier to prevent this default? Are there any other ways to download the file either in javascript or in html?
一种建议的解决方案是将URL读取为arrayBuffer,然后在DOM中创建一个新的blob,然后创建一个anchor元素,然后单击它..但这似乎很难强制下载文件.
One proposed solution is to read the URL as a arrayBuffer and then create a new blob in the DOM, and then create an anchor element and click it.. But that seems hacky to force a download of a file.
我确信他们必须是一种更干净的解决方案,以便从URL下载文件,这是一个小问题,希望有一个简单的解决方案.
I am sure their must be a cleaner solution to download a file form a URL, its a trivial problem, hoping for a simple solution.
谢谢.
推荐答案
您可以将文件作为blob提取并以相同的方式提供,不会有导致CORS问题的请求.
You can fetch the file as a blob and provide it the same way, there will be no request that leads into CORS issues.
模板
<a
:href="item.url"
v-text="item.label"
@click.prevent="downloadItem(item)" />
Vue
methods: {
downloadItem ({ url, label }) {
Axios.get(url, { responseType: 'blob' })
.then(response => {
const blob = new Blob([response.data], { type: 'application/pdf' })
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = label
link.click()
URL.revokeObjectURL(link.href)
}).catch(console.error)
}
}
注意:在我的示例中,我使用了Axios,但这不是必需的,为简单起见,blob的mime类型是硬连线的.
这篇关于Vue/HTML/JS如何使用下载标签将文件下载到浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!