在 Vue 项目中使用 <a>
标签在 Chrome 浏览器中下载文件,目前测试网络路径图片,网络路径 mp4 文件,都会直接在浏览器当前 tab 页打开,代码示例如下
<a href="http://v1.keepcdn.com/video/2019/12/14/21/51/15763314900925df4e8e265dcbb4382acc709.mp4" download>mp4</a>
<a href="https://img.36krcdn.com/20200305/v2_dfec2fe8a18b49eeb5a7b9960c2ad500_img_png" download>png</a>
Version
Chrome: Version 80.0.3987.132 (Official Build) (64-bit)
Vue: v2.6.10
解决思路
使用 fetch
获取 url 得到 blob 对象,下载 window.URL.createObjectURL()
生成的 object url 就行了
<template> <div> <a href="http://v1.keepcdn.com/video/2019/12/14/21/51/15763314900925df4e8e265dcbb4382acc709.mp4" download >mp4</a> <a href="https://img.36krcdn.com/20200305/v2_dfec2fe8a18b49eeb5a7b9960c2ad500_img_png" download >png</a> <a ref="download" :href="downloadUrl" :download="downloadFileName">download</a> <input type="button" @click="downloadClick" value="download" /> </div> </template> <script> export default { data () { return { downloadFileName: '', downloadUrl: '' } }, methods: { async downloadClick () { let url = 'http://v1.keepcdn.com/video/2019/12/14/21/51/15763314900925df4e8e265dcbb4382acc709.mp4' // 网络路径文件地址 const res = await fetch(url) console.log(res) const blob = await res.blob() console.log(blob) const urlBlob = window.URL.createObjectURL(blob) // 创建 object url,没有这一步下载的 blob 文件会出现 Failed 情况 console.log('urlBlob: ', urlBlob) this.downloadUrl = urlBlob console.log('downloadUrl: ', this.downloadUrl) this.downloadFileName = 'a.mp4' // 文件名需要动态赋值 console.log('fileName: ', this.downloadFileName) setTimeout(() => { this.$refs.download.click() }, 200) } } } </script>
参考
developer.mozilla.org/zh-CN/docs/…
developer.mozilla.org/zh-CN/docs/…