第一步:在upload使用的组件中定义空数组(在所有的filelist赋值中只能为数组,不能为对象)
第二步:配置props里面的属性
const props = {
name: 'file',
beforeUpload: this.beforeUpload,
fileList: this.state.fileList.slice(-1),
onRemove: file => {
this.setState(({ fileList }) => {
const index = fileList.indexOf(file);
const newFileList = fileList.slice();
newFileList.splice(index, 1);
return {
fileList: newFileList,
};
});
},
};
beforeUpload方法:
beforeUpload = file => {
const isExcel = file.name.split('.')[1] === 'xlsx';
const isExl = file.name.split('.')[1] === 'xls';
if (!isExcel && !isExl) {
message.error('请上传xlsx 和 xls 类型的文件!');
return false;
}
//对文件格式判断过后调用后端接口,返回结果为getCcpMarginExistsList
this.props.getCcpMarginExists({ fileName: file.name });
this.setState(() => ({
fileList: [file],
}));
return false;
};
第三步:对上传之前调用接口的返回数据进行是否上传的判断
const { getCcpMarginExistsList } = nextProps;
if (getCcpMarginExistsList !== this.props.getCcpMarginExistsList) {
if (_.get(getCcpMarginExistsList, 'retCode') !== '0') {
message.error(_.get(getCcpMarginExistsList, 'message') || '请重新上传文件');
this.setState({
fileList: [],
});
}
if (
_.get(getCcpMarginExistsList, 'retCode') === '0' &&
_.get(getCcpMarginExistsList, 'value') === true
) {
this.setState({
visible: true, // 弹出modal框,点击确定继续上传,点击取消放弃上传
});
}
if (
_.get(getCcpMarginExistsList, 'retCode') === '0' &&
_.get(getCcpMarginExistsList, 'value') === false
) {
this.handleUpload(); // 直接调用上传方法
}
}
上传方法:
handleUpload = () => {
const { uploadQuery } = this.props;
const { fileList } = this.state;
const formData = new FormData();
fileList.forEach(file => {
formData.append('file', file);
});
const action = `${window.location.origin}${uploadQuery}`;
reqwest({
url: action,
method: 'post',
processData: false, // 用于对data参数进行序列化处理
data: formData, // data必须为数组,否则会报错
success: result => {
this.setState({
fileList, // fileList赋值必须为数组,否则会报错
});
if (String(result.retCode) === '1') {
message.error(result.message || '上传失败!', 5);
} else {
message.success(result.message || '文件上传成功!', 5);
}
},
error: () => {
this.setState({
fileList: [], // fileList赋值必须为数组,否则会报错
});
},
});
this.setState({
visible: false,
});
};
Modal框:
<Modal // POSTTRADE-10968 CCP保证金页面功能 待发布
title="温馨提示"
visible={this.state.visible}
onOk={this.handleUpload}
onCancel={this.handleCancel}
maskClosable="true"
>
<h3>已存在相同日期保证金信息,是否覆盖?</h3>
</Modal>
handleCancel = e => {
this.setState({
visible: false,
fileList: [],
});
};