Antd Upload组件上传文件至php后端, php拿到对应的文件名(二: vue实现)
组件文件: UploadFile.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | <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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <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接口:
1 2 3 4 5 6 7 8 9 10 11 | public function upload() { $file = $_FILES [ 'file' ]; $path = $file [ 'tmp_name' ]; $data = ExcelModule::loadFile( $path ); // 得到返回的数据 log_message( $data ); return result(0, 'suc' , $data ); } |
ExcelModule::loadFile实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | /** * 读取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 ; } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)