上傳文件組件:UploadFile.jsx
import React from "react"; import * as antd from "antd"; const { Upload, Button, Icon, message } = antd; class Wrapper extends React.Component { state = {}; // 新打開界面 componentDidMount() {} onChange = ({ file }) => { if (file.status === "done") { message.success(`${file.name} file uploaded successfully`); console.log(file); const { response: { code, msg, data } } = file; this.props.onOk({ code, msg, data }); } else if (file.status === "error") { message.error(`${file.name} file upload failed.`); } }; // 渲染 render() { const { url } = this.props; const props = { name: "file", action: url, showUploadList: false, headers: { authorization: "authorization-text" }, onChange: this.onChange }; return ( <Upload {...props}> <Button style={{ marginLeft: 20 }} onClick={() => { console.log("hhhh"); }} > <Icon type="upload" /> 從文件導入 </Button> </Upload> ); } } export default Wrapper;
組件使用:
<UploadFile url='/api/login/upload' onOk={this.onOk.bind(this)} />
onOk 一般是放服務端處理完成后的后續操作!如:
onOk = res => { console.log('onOk', res); };
php 后端處理:
public function upload() { $file = $_FILES['file']; $path = $file['tmp_name']; $data = ExcelModule::loadFile($path); // 得到返回的數據 log_message($data); return result(0, 'suc', $data); }
ExcelModule::loadFile是讀取excel文件的內容,並返回array數據用的,實現如下:
public static function loadFile(string $filePath) { try { $reader = \PHPExcel_IOFactory::createReaderForFile($filePath); $excel = $reader->load($filePath); $sheet = $excel->getActiveSheet(); return $sheet->toArray(); } catch(\Exception $e) { log_message(sprintf('讀取excel文件失敗: file=%s, errorMsg=%s', $filePath, $e->getMessage())); } }