【vue】使用导出功能,后端返回数据流格式的处理

文章讲述了如何在接收到数据流格式的接口数据时,通过Blob对象进行解析处理,特别是针对Excel文件。然后通过创建HTML链接触发浏览器自动下载。整个过程涉及axios库的使用,设置responseType为blob,以及封装下载文件的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、当从接口获取的数据流格式的数据时,进行解析处理,使用blob转换

const blob = new Blob([res.data], {type: 'application/vnd.ms-excel; charset=utf-8'})

解析前的格式: 

 解析后的数据: 

二、创建链接实现浏览器自动下载 

 const link = document.createElement('a')
 link.href = URL.createObjectURL(blob)
 link.download = fileName
 link.click()
 URL.revokeObjectURL(link.href)

三、请求接口的时候注意类型

 {responseType: 'blob'}

 三、封装方法

function downloadFile (url, fileName, condition) {
    const hide = message.loading('下载中..', 0)
    let info = JSON.parse(JSON.stringify(condition))
    axios.post(url, {...info}, {responseType: 'blob'}).then(res => {
        if (res.code === 200) {
            hide()
            this.$message.error(res.message)
            return
        }
        const blob = new Blob([res.data], {type: 'application/vnd.ms-excel; charset=utf-8'})
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = fileName
        link.click()
        URL.revokeObjectURL(link.href)
        hide()
        this.$message.success('导出成功')
    }).catch(err => {
        hide()
        this.$message.error('导出失败')
    })
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值