1. 程式人生 > 其它 >Vue+ElementUI圖片上傳前進行圖片壓縮

Vue+ElementUI圖片上傳前進行圖片壓縮

圖片上傳使用的是ElementUI的Upload上傳元件,引數說明請檢視官網

頁面使用元件

<el-upload
	:action="upload_path" 
	list-type="picture-card"
	:data="upload_info"
	name="file"
	:on-success="uploadSuccess"
	:on-preview="handlePictureCardPreview"
	:on-remove="handleRemove"
	:before-upload="beforeAvatarUpload"
	:file-list="imgs"
	:show-file-list="true"
	accept="image/*">
		<i class="el-icon-plus" />
</el-upload>

引數定義

data() {
	return {
		imgs: [],
		// 圖片預覽
		dialogImageUrl: '',
		dialogVisible: false,
		upload_path: '圖片上傳api介面',
		// 上傳時附帶的額外引數
		upload_info: {
			type: 'img',
			data: '上傳時附帶的額外引數'
		},
		quality: 0.6, // 壓縮比例
	}
},

Upload元件呼叫的方法:

methods: {
	// 檔案上傳成功
    uploadSuccess(res) {
      if (res.code === 200) {
        this.imgs.push({ name: res.data, url: this.$fileUrl_ + '/' + res.data, path: res.data })
      } else {
        console.error('檔案上傳失敗', res.msg)
      }
    },
	// 上傳檔案之前
    beforeAvatarUpload(file) {
		// 圖片大小大於2M進行圖片壓縮
      if (file.size / 1024 / 1024 > 2) {
        const that = this
        return new Promise(resolve => {
          const reader = new FileReader()
          const image = new Image()
          image.onload = (imageEvent) => {
            const canvas = document.createElement('canvas') // 建立畫布
            const context = canvas.getContext('2d') 		// 畫布為2d
            const width = image.width * that.quality 		// 圖片寬度 * 壓縮比例
            const height = image.height * that.quality		// 圖片高度 * 壓縮比例
            canvas.width = width							// 畫布寬度
            canvas.height = height							// 畫布寬度
            context.clearRect(0, 0, width, height)
            context.drawImage(image, 0, 0, width, height)
            const dataUrl = canvas.toDataURL(file.type)		//圖片轉路徑
            const blobData = that.dataURLtoBlob(dataUrl, file.type) //圖片轉二進位制
            resolve(blobData)
          }
          reader.onload = e => { image.src = e.target.result }
          reader.readAsDataURL(file)
        })
      } else {
        return true
      }
    },
	//圖片轉二進位制
    dataURLtoBlob(dataURL, type) {
      var binary = atob(dataURI.split(',')[1])
      var array = []
      for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i))
      }
      return new Blob([new Uint8Array(array)], { type: type })
    },
	// 圖片移除
    handleRemove(file, fileList) {
      const arr = []
      fileList.forEach(r => {
        arr.push(r.response.data)
      })
      this.imgs = arr
    },
	// 圖片預覽
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
}

轉載:Vue+Element-UI實現上傳圖片並壓縮