Vue 上傳前獲取圖片寬度尺寸和大小


參考資料: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
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM