(一)先上頁面:
需求說明 :
(1) 可點擊上傳或者拖拽上傳
(2) 只能上傳tar格式並且不能超過10Mb
(3)上傳文件的列表會覆蓋上一個上傳的(即文件列表只能有一個文件)
(二)頁面代碼:
<el-upload class="upload-demo" drag :action="https://jsonplaceholder.typicode.com/posts/" :before-upload="beforeUpload" :on-success="upSuccess" :on-error="upError" :on-remove="upRemve" :on-change="upChange" enctype="multipart/form-data" :file-list="fileList" :multiple="false" > <i class="el-icon-upload"></i> <div class="el-upload__text"> 將文件拖到此處,或<em>點擊上傳</em> </div> <div class="el-upload__tip" slot="tip"> 只能上傳tar格式,且不超過10MB </div> </el-upload>
注:action為上傳文件的接口,:file-list已上傳的文件列表,:multiple指是否支持多選文件上傳
(三)上傳的鈎子函數
//上傳之前 beforeUpload(file) { const fileSuffix = file.name.substring( file.name.lastIndexOf('.') + 1 ); const whiteList = ['tar']; if (whiteList.indexOf(fileSuffix) === -1) { this.$message({ type: 'error', message: '上傳文件只能是 tar 格式', showClose: true, offset: 80, }); this.fileList = []; return false; } const isLt2M = file.size / 1024 / 1024 < 10; if (!isLt2M) { this.$message({ type: 'error', message: '上傳文件不能超過10MB', showClose: true, offset: 80, }); return false; } }, // 上傳成功 upSuccess(res) { this.$message({ type: 'success', message: '上傳成功', showClose: true, offset: 80, }) }, // 上傳失敗 upError() { this.$message({ type: 'error', message: '上傳失敗', showClose: true, offset: 80, }); }, //上傳的文件改變時(覆蓋原來的文件) upChange(file, fileList) { if (fileList.length > 0) { this.fileList = [fileList[fileList.length - 1]]; } }, // 移除列表 upRemve(file) { console.log(file)console.log(file) }
限制文件的格式還可以在html頁面中加入 :accept="["tar","txt"]"