后端返回二进制文件前端实现下载

后端返回的内容

在这里插入图片描述
传参后拿到的是上图显示的结果,前端如何实现下载此文件为excle或者zip呢?一起来看看吧:

前端实现下载

  • 在项目封装的统一请求的文件中加入responseType : "blob"即可。

    注意:该代码应与headers并列而不是包含,我在项目中不小心写入headers中,结果一直是乱码,耗时较长。以下是我加入responseType : "blob"的地方,根据自己项目封装的请求方法加入即可。

    在这里插入图片描述

  • 点击下载按钮时加入以下代码

    //按钮
    <el-button type="primary" @click="downLoadInventory">下载</el-button>
    
    //下载方法
    downLoadInventory(){
    	this.$http.inventoryTask.exportByTask(param).then((res) => {   //调接口传参
    
    		//下载zip
    		//  参数1:接口返回数据;参数2:blob文件类型;参数3:文件名称
            downLoadFile(res,'application/zip',"文件名" + '.zip');  //downLoadFile方法在下面
    
    		//下载excel
            //downLoadFile(res,'application/vnd.ms-excel',"文件名");
        }
    }
    
    //downLoadFile()
    downLoadFile(data,type,fileName) {
        const element= document.createElement('element');
        const blob = new Blob([data], {
            type: type
        })
        element.style.display = 'none';
        element.href = window.URL.createObjectURL(blob);  //可以打印看看blob
        element.download = fileName; //下载的文件名
        document.body.appendChild(element);
        element.click();
        window.URL.revokeObjectURL(element);  //释放
    }
    
    

这样就可以下载啦,有问题在评论区欢迎指出哦~ ❤️

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值