Vue + Element-ui upload 上传前压缩图片

李言
2023-12-01
<el-upload
              multiple
              :limit="2"
              :action="imgUpload.url + '?time=' + gettime"
              list-type="picture-card"
              :headers="imgUpload.headers"
              :on-success="handlePictureSuccess"
              :on-exceed="handleExceed"
              :before-upload="beforePictureUpload"
              :on-remove="handleRemove"
              :file-list="fileListShow"
              :on-preview="handlePictureCardPreview"
            >
              <i class="el-icon-plus"></i>
            </el-upload>

1.在beforeUpload方法中添加

beforeUpload(file) {
    let _this = this
    return new Promise((resolve, reject) => {
        let isLt2M = file.size / 1024 / 1024 < 10 // 判定图片大小是否小于10MB
        if(!isLt2M) {
            reject()
        }
        let image = new Image(), resultBlob = '';
        image.src = URL.createObjectURL(file);
        image.onload = () => {
            // 调用方法获取blob格式,方法写在下边
            resultBlob = _this.compressUpload(image, file);
            resolve(resultBlob)
        }
        image.onerror = () => {
            reject()
        }
    })
},
 
/* 图片压缩方法-canvas压缩 */
compressUpload(image, file) {
    let canvas = document.createElement('canvas')
    let ctx = canvas.getContext('2d')
    let initSize = image.src.length
    let { width } = image, { height } = image
    canvas. width = width
    canvas.height = height
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    ctx.drawImage(image, 0, 0, width, height)
    
    // 进行最小压缩0.1
    let compressData = canvas.toDataURL(file.type || 'image/jpeg', 0.1)
    
    // 压缩后调用方法进行base64转Blob,方法写在下边
    let blobImg = this.dataURItoBlob(compressData)
    return blobImg
},
 
/* base64转Blob对象 */
dataURItoBlob(data) {
    let byteString;
    if(data.split(',')[0].indexOf('base64') >= 0) {
        byteString = atob(data.split(',')[1])
    }else {
        byteString = unescape(data.split(',')[1])
    }
    let mimeString = data
        .split(',')[0]
        .split(':')[1]
        .split(';')[0];
    let ia = new Uint8Array(byteString.length)
    for( let i = 0; i < byteString.length; i += 1) {
        ia[i] = byteString.charCodeAt(i)
    }
    return new Blob([ia], {type: mimeString})
}

2.说明:

添加以上代码后,文件传输服务器的时候,传输的是压缩的文件,但在on-success钩子中,参数file、fileList中依然是原图片的信息,即未压缩的图片信息,所以,当在on-success中打印file时,如果打印的文件尺寸没有改变,并不是没有压缩传输成功。如果想要确定是否传输了压缩文件至服务器,可以在接口请求时让后台人员查看一下传输时的文件参数。

 类似资料: