beforeUpload方法中,除了可以返回圖片校驗時的true/false,還可以以return new Promise的方式返回文件,如返回文件,則上傳時,以返回的文件為准上傳。
eg:
beforeAvatarUpload(file) { // console.log('上傳前',file) const that = this const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' const isLt2M = file.size / 1024 / 1024 < 4 return (new Promise((resolve, reject) => { if (!isJPG) { this.$message.error('上傳圖片只能是 JPG 格式!') reject() } if (!isLt2M) { this.$message.error('上傳圖片大小不能超過 2MB!') reject() } if (this.isWH) { const that = this const url = window.URL || window.webkitURL const img = new Image() // 手動創建一個Image對象 img.src = url.createObjectURL(file)// 創建Image的對象的url img.onload = function() { if (that.width != this.width || that.height != this.height) { that.$notify({ title: '失敗', message: `上傳圖片分辨率建議${that.width}*${that.height},寬度不可超過${that.width}px,高度不超過${that.height}px!`, type: 'error', duration: 3000 }) that.$emit('IsImgValid') reject() } else { resolve(file) } } } })) },