使用input上传图片至七牛

 
getPositiveImg (el) {
      let file = el.target.files[0]
      this.type = 'positive'
      this.beforeUpload(file)
    },
 async beforeUpload (file) {
      const isLt = file.size / 1024 < this.byteSize
      if (!isLt) {
        this.$message.error(`上传图片大小不能超过 ${this.byteSize}KB!`)
        return false
      }
      let res = await this.$tool.getUploadToken(this, {
        mimeType: file.type || file.raw.type,
        type: 'IMAGE'
      })
      this.uploadFile(file, res)
    },
uploadFile (file, { token, fileName, fileUrl }) {
      const fd = new FormData()
      fd.append('token', token)
      fd.append('key', fileName)
      fd.append('file', file)
      var xhr = new XMLHttpRequest()
      var that = this
      xhr.open('POST', '**七牛地址**', true)
      return new Promise(resolve => {
        xhr.onload = function () {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              var data = JSON.parse(xhr.responseText)
              resolve(data.key)
            } else {
              console.log(xhr.statusText)
            }
          }
        }
        xhr.onerror = function (e) {
          console.log(xhr.statusText)
        }
        xhr.send(fd)
        that.$emit('input', this.type, fileUrl)
      })
    }

 

你可能感兴趣的:(js)