今天在工作中遇到这个问题:当我们上传文件的时候,需要限制文件的大小和文件的类型,这里文件的大小不超过10MB和上传的文件只能为图片。
<el-form-item label="合同文件" prop="path">
<el-upload
:disabled="!!rowData.path"
ref="uploadRef"
:action="uploaderUrl"
:data="{type: 3}"
:headers="headers"
accept=".docx"
:multiple="false"
:before-upload="handleBeforeUpload"
:on-success="handleOnSuccess"
:before-remove="handleBeforeRemove"
:on-remove="handleOnRemove">
<el-button size="small" type="primary" :disabled="!!rowData.path">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传.ppt,.docx,.excel文件,且不超过10MB!</div>
</el-upload>
上传 beforeAvatarUpload(file) {
console.log(file)
},我们可以看看file文件里面是什么内容
因此我们可以利用file.type里面来判断文件的类型,file.size来判断文件的大小
methods:{
/** 上传前 */
beforeAvatarUpload(file) {
const isJPG = file.type === "image/jpg";
const isPng = file.type==="image/png";
const isJpeg=file.type==="image/jpeg";
//1MB=1024*1024(1MB=1024KB 1KB=1024MB)
const is10M = file.size / 1024 / 1024 < 10;
//限制文件上传类型
if (!isJPG && !isPng && !isJpeg) {
this.$message.error("上传图片只能是 png,jpg,jpeg 格式!");
return false
}
//限制文件上传大小
if (!is10M) {
this.$message.error("上传图片大小不能超过 10MB!");
return false
}
return true
},
}
上传错误的效果如图所示: