超链接下载文件就是用a标签下载文件
非常简单
下面是封装的一个下载的组件的代码,仅供参考
<template>
<a
ref="link"
:href="url"
:download="fileName"
/>
</template>
<script>
export default {
name: 'HDownload',
props: {
hrefUrl: {
type: String,
default: ''
},
fileName: {
type: String,
default: ''
},
data: {
type: Object,
default: null
}
},
computed: {
url () { //
const downData = this.data
if (downData) {
const params = Object.keys(downData).map(function (key) {
const value = downData[key]
return typeof (value) !== 'undefined' && value !== null ? encodeURI(key) + '=' + encodeURI(value) : ''
}).join('&')
return this.hrefUrl.includes('?') ? '&' + params : '?' + params
}
return this.hrefUrl
}
},
methods: {
// 下载用API
download () {
this.$nextTick(() => {
this.$refs.link.click()
})
}
}
}
</script>
但是用超链接下载有一个弊端,就是对于xls文件 Microsoft Edge 浏览器下载会出问题,
会访问类似于这种的地址 具体原因可以自行百度这里只是有个解决办法https://view.officeapps.live.com/op/view.aspx?src=http%3A%2F%2Fyzqyfw.nbyz.gov.cn%3A30582%2Fuir_files%2Ffilemanager%2Fattach%2F20219%2Febf6f0eb16024419b7e6d2f7c97792fe.xls&wdOrigin=BROWSELINK
那么怎么解决呢 就是用iframe进行文件下载 ,就可以避免这类问题出现
代码如下
var url = record.fileUrl // 文件地址
var iframe = document.createElement('iframe')
iframe.src = url
iframe.style.display = 'none'
iframe.onload = function () {
console.debug('start downloading...')
document.body.removeAttribute(iframe)
}
document.body.appendChild(iframe)
望采纳