組件文件: UploadFile.vue
<template>
<a-upload
name="file"
:disabled="uploading"
:action="url"
v-bind="others"
:show-upload-list="false"
@change="change"
>
<a-button :loading="uploading">
<a-icon type="upload" />
{{ title }}
</a-button>
</a-upload>
</template>
<script>
export default {
name: 'FileImporter',
props: {
url: {
type: String,
required: true
},
title: {
type: String,
required: false,
default: '導入文件'
},
others: {
type: Object
}
},
data() {
return {
uploading: false
}
},
methods: {
change({ file }) {
this.uploading = file.status === 'uploading'
if (file.status === 'done') {
const {
response: { code, msg, data }
} = file
if (code === 0) this.$emit('ok', { code, msg, data })
else this.$message.warn(msg)
} else if (file.status === 'error') this.$message.error(`${file.name} file upload failed.`)
}
}
}
</script>
<style></style>
在Upload組件的change事件中監測file.status,控制外層Upload和Button的狀態,防止上傳過程中還能再次觸發文件上傳!
組件調用者: index.vue
<template>
<upload-file url="/api/login/upload" title="導入Excel文件" :others="others" @ok="ok" />
</template>
<script>
import UploadFile from '@/components/UploadFile'
export default {
components: {
UploadFile
},
data() {
return {
others: {
accept:
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel' // 限定上傳excel文件
}
}
},
methods: {
ok(res) {
console.log('onOk: ', res)
this.$message.success('謝謝, 成功了')
}
}
}
</script>
<style></style>
后端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數據
* @param $filePath
* @return 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)
{
$msg = sprintf('讀取excel文件失敗: file=%s, errorMsg=%s', $filePath, $e->getMessage());
log_message($msg);
return $msg;
}
}
