// 對接
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':''"
/>