页面
<el-upload
class="avatar-uploader"
action="https://com/posts/"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="uploadBefore">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
js代码
uploadBefore(file,done) {
console.log(file);
const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
const isLt1M = file.size / 1024 / 1024 < 1;
if (!isJPG) {
this.$message.error('上传头像图片只能是JPG/PNG/JPEG格式!')
}
if (!isLt1M) {
this.$message.error('上传头像图片大小不能超过1MB!')
}
let _this = this
let imgWidth = ''
let imgHeight = ''
let width = 700
let height = 300
const isSize = new Promise(function (resolve, reject) {
console.log(width, height)
let _UPL = window.URL || window.webkitURL;
let img = new Image();
img.src = _UPL.createObjectURL(file)
img.onload = function () {
imgWidth = img.width
imgHeight = img.height
let valid = img.width <= width && img.height <= height
valid ? resolve() : reject();
}
}).then(
()=>{
return file
},
()=>{
_this.$message.error({
message :'上传的图片大小不符合标准,宽需要为' + width + 'px,高需要为' + height + 'px。当前上传图片的宽高分别为'+ imgWidth + 'px和' + imgHeight + 'px',
btn:false,
})
done();
return Promise.reject(false)
})
console.log(isSize)
done();
return isJPG && isLt1M && isSize
//如果你想修改file文件,由于上传的file是只读文件,必须复制新的file才可以修改名字,完后赋值到done函数里,如果不修改的话直接写done()即可
//var newFile = new File([file], {type: file.type});
//done(newFile)
},