antd Upload 上传时只触发Uploading状态,无法获取服务器返回的response
最近在对接antd Upload时候 想获取服务器返回的数据图片,发现无法获取返回值
1、场景分析,根据官网可以知道。chang事件会调用三次,三次有什么不同呢
2、bug 重现
1、我是在a-upload 的组件上直接绑定了一个change事件 @chang=‘handleChange’ 并且绑定了file-list=‘myList’,
2、属性说明 :file-list: 文件目录属性 @chang 改变事件回调 三个状态根据官方可以知是 done (成功) uploading(上传中) error(出错)
// chang事件
handleChange({ file }) {
console.log('改变状态', file);
//this.myFileList = fileList;
if (file.status === 'uploading') {
this.loading = true;
return;
}
if (file.status === 'done') {
this.imageUrl = file.response.data;
if (this.urlData[this.ocrType]) {
console.log('返回的链接', this.imageUrl);
this.loading = false;
this.urlData[this.ocrType]({ ocrPictureUrl: file.response.data }).then((data) => {
this.callBack(true, this.imageUrl, data.data, false);
});
} else {
this.callBack(true, this.imageUrl, null, false);
}
}
},
3、根据控制台的结果发现只有一种Uploading,上传图片和文件时只触发了一次
3、解決bug 检查file-list
原来从服务器返回的时候 ,我们要将回调文件放到本地的时候,才能从 handleChange({ file }) { 中的file进行获取转状态,所有有一步骤非常关键。其中{file}是es6的语法取出文件里的file数据
1、确认a-upload 的fileList-list 是否有加上
2、在@chang事件里 是否有将 file 赋值给我们的myFileList (自己定义的
3、所以在把赋值加上就可以拿到返回的三种状态了,我们通过file.status 去控制某种状态的下的操作
handleChange({ file,fileList }) {
this.myFileList = fileList
}
改完的完整代码如下
// chang事件
handleChange({ file,fileList }) {
console.log('改变状态', file);
this.myFileList = fileList;
if (file.status === 'uploading') {
this.loading = true;
return;
}
if (file.status === 'done') {
this.imageUrl = file.response.data;
if (this.urlData[this.ocrType]) {
console.log('返回的链接', this.imageUrl);
this.loading = false;
this.urlData[this.ocrType]({ ocrPictureUrl: file.response.data }).then((data) => {
this.callBack(true, this.imageUrl, data.data, false);
});
} else {
this.callBack(true, this.imageUrl, null, false);
}
}
},