后端返回数据流,前端如何导出word,excel文件

本文介绍了如何使用axios进行POST请求下载Excel和Word文件,通过设置responseType为'arraybuffer',并利用Blob对象和URL.createObjectURL创建可下载链接。

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

 

一般情况下如果是get请求,我们可以直接把下载地址用新窗口打开,浏览器就会自动下载。

如果后端接口需要post请求,前端又该如何下载呢,一般后端接口以数据流形式返回到前端。

以axios(例子axios 进一步封装了,只做参考)为例:

excel文件,需要注意的是,相应类型 responseType: "arraybuffer" 需要添加上。

axios({
                type:'post',
                path:'/tesUrl',
                data:data,
                opts:{responseType: "arraybuffer"},
                fn:(data,res)=>{
                    const url = window.URL.createObjectURL(new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}));
                        const link = document.createElement('a');
                        link.style.display = 'none';
                        link.href = url;
                        let fileNameHeader=res.headers['content-disposition'];
                        link.download = decodeURIComponent(fileNameHeader.substring(fileNameHeader.indexOf('=')+1));
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        this.timer = setTimeout(()=>{
                            this.$message.success('导出成功');
                        }, 1000)
                },
                errFn:error=>{
                    console.log(error);
                    this.$message.error(error);
                }
            });

word文件:

axios({
                    type:'post',
                    path:'testUrl',
                    data:{id:id},
                    opts:{responseType: "arraybuffer"},
                    fn:(data,res)=>{
                        const url = window.URL.createObjectURL(new Blob([res.data], {type: "application/msword"}));
                            const link = document.createElement('a');
                            link.style.display = 'none';
                            link.href = url;
                            let fileNameHeader=res.headers['content-disposition'];
                            link.download = decodeURIComponent(fileNameHeader.substring(fileNameHeader.indexOf('=')+1));
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                            this.timer = setTimeout(()=>{
                                this.$message.success('导出成功');
                            }, 1000)
                    },
                    errFn:error=>{
                        console.log(error);
                        this.$message.error(error);
                    }
                });

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值