饿了么中的Upload组件已经提供了限制用户上传的图片格式和大小的例子(https://element.eleme.io/#/zh-CN/component/upload),在此又新加图片的尺寸
<el-upload
class="avatar-uploader"
action=""
:show-file-list="false"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
before-upload | 上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。 |
主要就是在上传之前做一些判断处理
<script>
export default {
data() {
return {
imageUrl: ''
};
},
methods: {
// 文件上传之前做处理
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
// 图片格式
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
return false;
}
// 图片大小
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
return false;
}
// 图片尺寸
let imgWidth="";
let imgHight="";
const isSize = new Promise(function (resolve, reject) {
const _URL = window.URL || window.webkitURL;
const img = new Image();
img.onLoad = function () {
imgWidth = img.width;
imgHight = img.height;
const status = img.width === 240 && img.height === 240;
status ? resolve() : reject();
}
img.src = _URL.createObjectURL(file);
}).then(()=>{
this.uploadImg(file); // 调用后台接口上传图片的方法
}).catch(()=>{
this.$message.warning({message: '上传文件的图片大小不合符标准,尺寸为240×240。当前上传图片的尺寸为:'+imgWidth+'×'+imgHight})
})
},
async uploadImg(file) {
const result = await equityManagementModels.getImageUrl(file);
this.imageUrl = result;
},
}
}
</script>
上述方案是使用自动上传,利用上传之前的函数做判断;
此外还可以使用手动上传的方式,即auto-upload属性设置为false,利用on-change事件来判断
<el-upload
class="avatar-uploader"
action=""
:auto-upload="false"
:on-change="handleChange">
</el-upload>
判断的js和之前基本相同 只有一个参数需要变化