參考資料:https://www.cnblogs.com/wyx-remove-love/p/wyx-20190626-1.html
https://blog.csdn.net/qq_22771739/article/details/87007191
廢話不多說,直接上代碼了
beforeAvatarUpload(file) { const isImg = file.type === 'image/jpeg' || file.type === 'image/png' const isLt2M = file.size / 1024 / 1024 < 5 if (!isImg) { this.$notify({ title: '失敗', message: '上傳圖片只能是 JPG/JPEG/PNG 格式!', type: 'error', duration: 3000 }) return false } if (!isLt2M) { this.$notify({ title: '失敗', message: '上傳圖片大小不能超過 4MB!', type: 'error', duration: 3000 }) return false } var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function () { //讓頁面中的img標簽的src指向讀取的路徑 var img = new Image() img.src = reader.result if (img.complete) {//如果存在瀏覽器緩存中 if (img.width > 540 || img.height > 300) { this.$notify({ title: '失敗', message: '上傳圖片分辨率建議540*300,寬度不可超過540px,高度不超過300px!', type: 'error', duration: 3000 }) return false } } else { img.onload = function () { if (img.width > 540 || img.height > 300) { this.$notify({ title: '失敗', message: '上傳圖片分辨率建議540*300,寬度不可超過540px,高度不超過300px!', type: 'error', duration: 3000 }) return false } } } } return isImg && isLt2M }