Element UI 上傳檔案 el-upload —— 手動上傳檔案,限制上傳檔案數量,檔案型別校驗等
阿新 • 來源:網路 • 發佈:2021-02-05
技術標籤:Element UI
目錄

手動上傳
:auto-upload="false"
this.$refs.upload.submit();
選擇檔案時,限定檔案型別
accept=".xlsx,.xls"
選擇檔案時,限制檔案總數
:limit="1"
超出檔案總數時,觸發
:on-exceed='limitCheck'
// 選擇的檔案超出限制的檔案總數量時觸發
limitCheck() {
this.$message.warning('每次只能上傳一個檔案')
},
檔案上傳前的檔案型別和檔案大小校驗
:before-upload="beforeUpload"
// 檔案上傳前的校驗 —— 常見的校驗有:校驗檔案型別,檔案大小
beforeUpload(file) {
// 允許上傳的檔案格式列表
let acceptList = ["xlsx", "xls"]
// 根據檔名獲取檔案的字尾名
let fileType = file.name.split('.').pop().toLowerCase()
// 判斷檔案格式是否符合要求
if (acceptList.indexOf(fileType) === -1) {
this.$message.error('只能上傳 xlsx/xls 格式的檔案 !');
return false
}
// 判斷檔案大小是否符合要求
if (file.size / 1024 / 1024 > 1) {
this.$message.error('上傳檔案大小不能超過 1M !');
return false
}
}
完整範例程式碼
<template>
<div style="padding: 30px">
<el-upload
ref="upload"
accept=".xlsx,.xls"
:limit="1"
:on-exceed='limitCheck'
:file-list="fileList"
:on-remove="removeFile"
:on-change="fileChange"
:auto-upload="false"
:before-upload="beforeUpload"
action="https://jsonplaceholder.typicode.com/posts/"
>
<el-button slot="trigger" size="small" type="primary">選取檔案</el-button>
<el-button :disabled="fileList.length<1" style="margin-left: 10px;" size="small" type="success"
@click="submitUpload">上傳到伺服器
</el-button>
<div slot="tip" class="el-upload__tip">只能上傳 xlsx/xls 檔案,且不超過1M</div>
</el-upload>
</div>
</template>
<script>
export default {
data() {
return {
fileList: []
}
},
methods: {
// 選擇檔案、移除檔案、上傳檔案成功/失敗後,都會觸發
fileChange(file, fileList) {
this.fileList = fileList
},
// 移除檔案時觸發
removeFile(file, fileList) {
this.fileList = fileList
},
// 選擇的檔案超出限制的檔案總數量時觸發
limitCheck() {
this.$message.warning('每次只能上傳一個檔案')
},
// 點選上傳按鈕
submitUpload() {
// 將檔案上傳到伺服器,先觸發beforeUpload事件,對上傳的檔案進行校驗,校驗通過後才會上傳
this.$refs.upload.submit();
},
// 檔案上傳前的校驗 —— 常見的校驗有:校驗檔案型別,檔案大小
beforeUpload(file) {
// 允許上傳的檔案格式列表
let acceptList = ["xlsx", "xls"]
// 根據檔名獲取檔案的字尾名
let fileType = file.name.split('.').pop().toLowerCase()
// 判斷檔案格式是否符合要求
if (acceptList.indexOf(fileType) === -1) {
this.$message.error('只能上傳 xlsx/xls 格式的檔案 !');
return false
}
// 判斷檔案大小是否符合要求
if (file.size / 1024 / 1024 > 1) {
this.$message.error('上傳檔案大小不能超過 1M !');
return false
}
}
},
}
</script>
<style scoped>
</style>
