blob数据流转为json格式

下载zip文件流当遇到下载失败的时候,就需要将后台错误信息返回给用户看,但是responseType: "blob"格式默认转为二进制。所以当下载错误的时候需要转为json格式,拿到code将错误信息返回给用户.

不多说了,直接上代码:

.then(result=>{console.log(result)if(result.type=="text/html"){constreader=newFileReader();reader.onload=function(){const{msg}=JSON.parse(reader.result);//此处的msg就是后端返回的msg内容that.$message({message:msg,type:"warning"});};reader.readAsText(result);}elseif(result.type=="application/zip"){constblob=result;constreader=newFileReader();reader.readAsDataURL(blob);reader.onload=e=>{consta=document.createElement("a");a.download=`商品清单.zip`;// 后端设置的文件名称在res.headers的 "content-disposition": "form-data; name=\"attachment\"; filename=\"20181211191944.zip\"",a.href=e.target.result;document.body.appendChild(a);a.click();document.body.removeChild(a);};}

作者:前端搬砖工小陈

链接:https://www.jianshu.com/p/84a2d8863799

来源:

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(blob数据流转为json格式)