现实中我们很多的需求是利用element的upload的ui来做上传功能,但是我们自己写上传规则,所以我们把上传规则写在before-upload里面 最后return false这样element就不会继续执行上传逻辑了
- 页面ui部分代码
<el-upload class="upload-demo" accept=".jpg,.jpeg,.png" action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false" :before-upload="beforeAvatarUpload" > <img v-if="addform.img_path" :src="this.$baseURL+'/'+addform.img_path" class="avatar"> <div class="form-upload-defult" v-else> <div class="img">编辑</div> <div class="text"> <p>上传营养品图片</p> <p>支持上传jpg、jpeg、png文件,且不超过800kb</p> </div> </div> </el-upload>
- js部分代码
我们利用axios 进行上传 因为涉及到跨域 beforeAvatarUpload(file) { const isJPG = file.type === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 0.8; // if (!isJPG) { // this.$message.error('上传头像图片只能是 JPG 格式!'); // } if (!isLt2M) { this.$message.error('上传头像图片大小不能超过 800k!'); return false; } let formData = new FormData() formData.append('file_path', file) this.$axios.post(`p/cater/caterUpload`, formData).then(response => { if (response.code == 0) { this.addform.img_path = response.data; } else { this.$message({ message: response.message, type: 'error' }) } }).catch((error) => { console.log(error) }) // return isJPG && isLt2M; return false; },