在before-upload方法中對圖片文件進行處理,並返回處理后的文件


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)
            }
          }
        }
      }))
    },

 


免責聲明!

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



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