vue实现下载TXT格式文件

2,435 阅读1分钟

这个项目导出功能是通过请求后台接口,后台会返回一个URL,前端直接打开这个URL进行下载的,EXC表格下载是没有问题的,但是浏览器默认TXT文件是直接打开的,所以我们要对TXT文件进行一些处理,利用a标签进行下载。

 exportType(row) {
            let obj = {
                id: this.id,
                type: row.value
            }
            api.deriveNumberPhone({
                ...obj
            }).then(res => {
                if (res.data.code == 10000 && res.data.data[0]) {
                    // window.location.href = res.data.data[0]
                    this.downloadFile(res.data.data[0])
                } else {
                    this.$message.error('暂无可导出的数据')
                }
                console.log(res, '导出')
            })
        },
        // 下载TXT文件
        downloadFile(url) {
            console.log(url)
            const link = document.createElement('a')
            fetch(url).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
                link.href = URL.createObjectURL(blob)
                // console.log(link.href)
                link.download = ''
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
            })
        },