前端导出文件流

方式一

clickExport() {
            axios({
                method: 'get',
                url: 'xxx/xxx',
                params: {   },
                headers: {
                    Authorization: `Bearer ${this.token}`
                },
                responseType: 'blob'
            }).then(resp => {
                this.exportLoading = false

                const link = document.createElement('a')
                const blob = new Blob([resp.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
                link.style.display = 'none'
                link.href = URL.createObjectURL(blob)
                link.setAttribute('download', decodeURI('数据导出.xlsx'))
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
            }).catch(error => {
                this.exportLoading = false
                console.error('文件导出失败...', error)
            })
        },

方式二

api.interceptors.response.use(
    response => {
        const res = response.data
        // 处理Excel下载
        if (response.config?.responseType === 'blob') {
            const blob = new Blob([res], { type: response.headers['content-type'] })
            const filename = window.decodeURI(response.headers['content-disposition']?.split('=')[1], 'UTF-8')
            const link = document.createElement('a')
            const url = URL.createObjectURL(blob)
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', filename)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            URL.revokeObjectURL(url) // 释放掉blob对象
            return
        }

        if (!res.code) {
            return Promise.resolve(res)
        }

    },
    error => {
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

 

上一篇:前端表格数据导出为excel表


下一篇:heic格式转码