实现限制上传文件类型(在上传前进行验证)
<template>
<el-upload
action="/upload"
:before-upload="handleBeforeUpload"
:on-success="handleSuccess"
>
<el-button slot="trigger">点击上传</el-button>
</el-upload>
</template>
<script>
export default {
methods: {
handleBeforeUpload(file) {
const fileType = file.type;
const allowedTypes = ['image/jpeg', 'image/png']; // 允许上传的文件类型
if (!allowedTypes.includes(fileType)) {
this.$message.error('只允许上传JPEG和PNG格式的图片');
return false; // 阻止文件上传
}
return true; // 允许文件上传
},
handleSuccess(response, file) {
// 处理上传成功的回调
},
},
};
</script>
一些常见的文件类型及其对应的MIME类型
图片文件:
JPEG图片:image/jpeg
PNG图片:image/png
GIF图片:image/gif
BMP图片:image/bmp
SVG图片:image/svg+xml
文档文件:
PDF文档:application/pdf
Word文档:*.doc application/msword
*.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
Excel表格:*.xls application/vnd.ms-excel
*.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
PowerPoint演示文稿:application/vnd.ms-powerpoint
文本文件:text/plain
压缩文件:
ZIP压缩包:application/zip
RAR压缩包:application/x-rar-compressed
7z压缩包:application/x-7z-compressed
tar压缩包:application/x-tar
视频文件:
MP4视频:video/mp4
AVI视频:video/x-msvideo
MOV视频:video/quicktime
WMV视频:video/x-ms-wmv
音频文件:
MP3音频:audio/mpeg
WAV音频:audio/wav
OGG音频:audio/ogg
FLAC音频:audio/flac