将定义为Blob类型的数据转换成Json类型的数据

277 阅读1分钟

问题描述

使用axios实现post请求方式下载文件时,需要将返回的数据类型提前定义为Bolb类型,表示其返回的是一个文件;在正常情况下后端返回到前端的是一个文件,但是当出现前端提交的参数错误或后端的程序运行异常等等情况时,后端返回给前端的数据就应该变为Json类型的数据,方便前端对错误信息等进行弹窗

解决方法

axios.post(`${BASEURL}/mobileoperator/mobileOperatorInvitation/dataCollation`,
          this.map, {responseType: 'blob'}).then(response => {

    /* 判断返回的数据类型是否为json类型 */
    if (response.data.type === "application/json") {
	
        /* 创建读取文件对象 */
        let fileReader = new FileReader();
        /* 读取文件数据 */
        fileReader.readAsText(response.data, 'utf-8')
        /* 请求完结事件 */
        fileReader.addEventListener("loadend", () => {

            /* 数据转json类型 */
            let parse = JSON.parse(fileReader.result);
            /* 此处的baseResponse为后端返回的键,可按对应的后端返回类修改 */
            let baseResponse = parse.baseResponse;
	
            /* iView异常弹窗 */
            this.$Notice.error({
                desc: baseResponse.message,
                duration: 1
            })
        })
    }
})