// 对接
export = (e) => {
e.preventDefault();
if (!this.state.selectTime) {
message.error('请选择时间');
return
}
/****/ FormData 对象使用
/****/ 1.用一些键值对来模拟一系列表单控件:即把form中所有表单元素的name与value组装成一个 queryString
/****/ 2. 异步上传二进制文件。
// 1.创建一个空对象实例( FormData类型其实是在XMLHttpRequest 2级定义的,它是为序列化表以及创建与表单格式相同的数据(是用于XHR传输)提供便利。)
let fileInfo = new FormData(); //(此时就可以调用 append 方法来添加数据)
if (this.state.file.size) { // 将要传递的参数全部封装到 fileInfo 参数中
fileInfo.append('type', this.state.type); // 可以同过 .get 方法来获取里面的 value
fileInfo.append('selectTime', this.state.selectTime);
fileInfo.append('file',this.state.file); // 通过 FormData将文件转为二进制
}
console.log(fileInfo.get('file')); // 获取文件信息
this.setState({confirmLoading: true});
let urlPre = process.env.NODE_ENV === 'production' ? (window.location.origin || (window.location.protocol + '//' + window.location.host)) : '/api';
$.ajax({
url: urlPre + '/reportImport/readExcelData',
type: 'post',
data: fileInfo, // 上传 fileInfo 封装的数据 ,传递给后台
contentType: false, //必须写这个,防止和 form 中的 content-type 起冲突,不设置 content-type 请求头
processData: false, //是否序列化 data 属性,解决illegal invocation报错的问题,(tip:设置false时type必须为post),
success: (data) => {
if (data.code == '00' && data.data) {
message.success('导入成功');
this.props.selectChange({pageNum: 1});
setTimeout(() => {
this.setState({
confirmLoading: false,
});
}, 500);
this.handleCancel();
} else if (data.code == '01') {
message.error(data.codeMsg);
this.setState({
confirmLoading: false,
});
this.handleCancel();
} else {
message.error("出错啦");
this.setState({
confirmLoading: false,
});
this.handleCancel();
}
}
});
this.setState({
visible: false,
});
};
// 上传文件
upload = () => {
// 初始化 ---- 获取到的文件
this.setState({
file: this.refs.file.files[0] // 获取选中的文件 this.refs.file.files[0]
});
// this.state.file.size 获取到的默认单位(字节)-转 M
let fileSize = (this.state.file.size) / 1024;
if (fileSize > 2048) {
message.error(' 文件大小不得超过 2M ');
return
}
};
<input
placeholder="选择文件"
type='file'
style={{width: 320, display: 'inline-block',}}
name="upload"
ref='file'
onChange={this.upload}
// accept 规定能够通过文件上传进行提交的文件类型(在服务器端验证文件上传)
accept="excel?'application/vnd.ms-excel':upFile?'application/pdf,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document':''"
/>