vue中的el-upload组件,上传文件之前,判断文件格式
<el-upload
class="avatar-uploader"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:http-request="upload"
:accept="accept"
action=""
:before-upload="beforeAvatarUpload" >
</el-upload>
props: {
allowFile: {
type: Array,
default: ()=>[],
}
},
methods: {
beforeAvatarUpload(file) {
if (this.allowFile) {
let fileTest = file.name.substring(file.name.lastIndexOf('.') + 1);
let allowFile = this.allowFile;
if (allowFile.length > 0 && allowFile.indexOf(fileTest) === -1) {
this.$message.error('文件格式不符合要求,请重新上传。');
return false;
}
}
let isLimit = file.size / (1024 * 1024) < this.maxSize;
if (!isLimit) {
this.$message.error(`文件大小必须小于${this.maxSize}MB`);
}
return isLimit;
},
}
父组件引用
<UploadFile
v-model="form.fileName"
accept="image/png,image/jpg,image/jpeg,.js,.html,.css"
:max-size="2"
:allowFile = "allowFile"
tip="支持的文件格式:js、html、css、jpg、jpeg、png。"
@change="getFileDetail"
/>
data() {
return {
allowFile: ['png', 'jpg', 'jpeg', 'js', 'css', 'html'],
}
},