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