Vue:使用elementUI upload組件上傳excel文件
elementUI官方的upload組件文檔可點此查看。
頁面效果如下所示,支持文件的二次確認上傳
demo中僅以excel舉例,若需要支持其他格式,可修改accept值,具體代碼如下:
<template> <div> <el-upload drag :limit=limitNum :auto-upload="false" accept=".xlsx" :action="UploadUrl()" :before-upload="beforeUploadFile" :on-change="fileChange" :on-exceed="exceedFile" :on-success="handleSuccess" :on-error="handleError" :file-list="fileList"> <i class="el-icon-upload"></i> <div class="el-upload__text">將文件拖到此處,或<em>點擊上傳</em></div> <div class="el-upload__tip" slot="tip">只能上傳xlsx文件,且不超過10M</div> </el-upload> <br/> <el-button size="small" type="primary" @click="uploadFile">立即上傳</el-button> <el-button size="small">取消</el-button> </div> </template> <script> export default { data() { return { limitNum: 1, // 上傳excell時,同時允許上傳的最大數 fileList: [], // excel文件列表 } }, methods:{ // 文件超出個數限制時的鈎子 exceedFile(files, fileList) { this.$message.warning(`只能選擇 ${this.limitNum} 個文件,當前共選擇了 ${files.length + fileList.length} 個`); }, // 文件狀態改變時的鈎子 fileChange(file, fileList) { console.log(file.raw); this.fileList.push(file.raw) ; console.log(this.fileList); }, // 上傳文件之前的鈎子, 參數為上傳的文件,若返回 false 或者返回 Promise 且被 reject,則停止上傳 beforeUploadFile(file) { console.log('before upload'); console.log(file); let extension = file.name.substring(file.name.lastIndexOf('.')+1); let size = file.size / 1024 / 1024; if(extension !== 'xlsx') { this.$message.warning('只能上傳后綴是.xlsx的文件'); } if(size > 10) { this.$message.warning('文件大小不得超過10M'); } }, // 文件上傳成功時的鈎子 handleSuccess(res, file, fileList) { this.$message.success('文件上傳成功'); }, // 文件上傳失敗時的鈎子 handleError(err, file, fileList) { this.$message.error('文件上傳失敗'); }, UploadUrl:function(){ // 因為action參數是必填項,我們使用二次確認進行文件上傳時,直接填上傳文件的url會因為沒有參數導致api報404,所以這里將action設置為一個返回為空的方法就行,避免拋錯 return "" }, uploadFile() { if (this.fileList.length === 0){ this.$message.warning('請上傳文件'); } else { let form = new FormData(); form.append('file', this.fileList); this.$axios({ method:"post", url: "/statistical/uploadbug", headers:{ 'Content-type': 'multipart/form-data' }, data:form }).then( res=>{ },err =>{ }); } } } } </script> <style scoped> </style>
來源於:https://blog.csdn.net/lt326030434/article/details/101214824