一、設置限制文件類型
通過Element的el-upload組件設置限制文件類型,只有特定的文件才能被上傳。
<el-upload
:auto-upload="false"
:on-change="handleChange"
:before-upload="handleBeforeUpload"
:file-list="fileList"
:accept="acceptType"
:action="uploadUrl">
<el-button slot="trigger" type="primary">選取文件</el-button>
<el-button style="margin-left: 10px;" type="success" :disabled="!fileList.length" @click="submitUpload">上傳到服務器</el-button>
</el-upload>
其中,acceptType就是限制的文件類型,可以是字符串,表示只允許一種類型,比如’image/jpeg’;也可以是數組,表示允許多種類型,比如[‘image/jpeg’, ‘image/png’];
二、設置提示信息
當上傳的文件類型不符合要求時,需要給用戶以相應的提示信息。
<el-upload
:auto-upload="false"
:on-change="handleChange"
:before-upload="handleBeforeUpload"
:file-list="fileList"
:accept="acceptType"
:action="uploadUrl">
<el-button slot="trigger" type="primary">選取文件</el-button>
<el-button style="margin-left: 10px;" type="success" :disabled="!fileList.length" @click="submitUpload">上傳到服務器</el-button>
<div slot="tip" class="el-upload__tip">只能上傳{{acceptType}}格式的文件</div>
</el-upload>
在el-upload組件中,使用slot=”tip”來設置提示信息,在其中加入class=”el-upload__tip”使提示信息顯示為紅色字體。
三、限制文件大小
除了限制文件類型,還可以通過設置最大文件大小來限制文件的上傳。
<el-upload
:auto-upload="false"
:on-change="handleChange"
:before-upload="handleBeforeUpload"
:file-list="fileList"
:accept="acceptType"
:action="uploadUrl"
:before-upload="beforeAvatarUpload">
<el-button slot="trigger" type="primary">選取文件</el-button>
<el-button style="margin-left: 10px;" type="success" :disabled="!fileList.length" @click="submitUpload">上傳到服務器</el-button>
<div slot="tip" class="el-upload__tip">只能上傳{{acceptType}}格式的文件,且大小不能超過{{maxSize/1024/1024}}MB</div>
</el-upload>
其中,beforeAvatarUpload是上傳前的回調函數,對於超過限制大小的文件進行篩選。
四、完整代碼示例
<template>
<div class="upload-demo">
<el-upload
:auto-upload="false"
:on-change="handleChange"
:before-upload="beforeAvatarUpload"
:file-list="fileList"
:accept="acceptType"
:action="uploadUrl">
<el-button slot="trigger" type="primary">選取文件</el-button>
<el-button style="margin-left: 10px;" type="success" :disabled="!fileList.length" @click="submitUpload">上傳到服務器</el-button>
<div slot="tip" class="el-upload__tip">只能上傳{{acceptType}}格式的文件,且大小不能超過{{maxSize/1024/1024}}MB</div>
<el-progress :percentage="uploadPercentage" v-if="showProgress"></el-progress>
</el-upload>
</div>
</template>
<script>
export default {
data() {
return {
fileList: [], //上傳的文件列表
acceptType: ['jpg', 'jpeg', 'png'], //限制的文件類型
maxSize: 20 * 1024 * 1024, //限制的文件大小,單位是位元組
uploadUrl: '', //上傳的接口
showProgress: false, //是否展示上傳進度條
uploadPercentage: 0, //上傳進度百分比
};
},
methods: {
handleChange(file, fileList) {
this.fileList = fileList;
},
beforeAvatarUpload(file) {
const isJPG = this.acceptType.indexOf(file.type.split('/')[1]) !== -1;
const isLtSize = file.size / 1024 / 1024 {
this.showProgress = false;
this.uploadPercentage = 0;
this.$message({
message: '上傳成功',
type: 'success'
});
})
.catch(error => {
console.log(error);
this.showProgress = false;
this.uploadPercentage = 0;
this.$message.error('上傳失敗');
});
}
}
}
</script>
原創文章,作者:HPMEE,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/371658.html