您的位置:首页 > Web前端 > Vue.js

vue项目中文件下载踩坑之路

2019-05-29 17:40 190 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/qq_41950018/article/details/90675063

最近工作中用到了文件的下载功能,文件的下载不能简单用ajax请求,文件下载还会涉及到http跨域问题,于是搜集了各种方法,一步步踩坑,终于有点眉目了。

方法一:a标签下载

利用a标签的href属性,但是遇到的问题是,我这边拿到的url是跨域的,在给文件设置名称的时候,a标签的download属性无效。找了很多资料也没能解决,想哭。

代码如下:

[code] if (!url) {
return
}
let link = document.createElement('a')
link.setAttribute('download', this.cOrderNo + '.zip')
link.style.display = 'none'
link.href = url
document.body.appendChild(link)
link.click()

方法二:form进行文件下载

这里是灵活用到了form的action,method,将请求嵌入到form的属性中,可以利用form中的input框进行传参,如果遇到accessToken的问题,可以在form的header中设置

代码如下:

[code]let accessToken = getToken()
let form = document.createElement('form')
let headerParam = {}
headerParam.Authorization = accessToken
form.setAttribute('header', headerParam)
form.setAttribute('style', 'display:none')
form.setAttribute('method', 'get')
let inputFileId = document.createElement('input')
inputFileId.setAttribute('type', 'hidden')
inputFileId.setAttribute('name', 'fileIds')
inputFileId.setAttribute('value', params.fileIds)
form.append(inputFileId)
let inputFileName = document.createElement('input')
inputFileName.setAttribute('type', 'hidden')
inputFileName.setAttribute('name', 'packageName')
inputFileName.setAttribute('value', params.packageName)
form.append(inputFileName)
form.setAttribute('action', '/ares/material/download')
form.setAttribute('target', '')
document.body.appendChild(form)
form.submit()

三、插件downloadjs

这个插件还是好用的,但是好像有跨域的问题不能解决,如果下载的链接不跨域的话,可以使用没问题,而且这个的使用方式比较简单,npm安装就可以。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: