前端vue图片压缩上传(upload+image-conversio)

插件安装

npm i image-conversion --save

插件引入imageConversion

import * as imageConversion from 'image-conversion';

注意直接引入 import imageConversion from ‘image-conversion’ 不生效

el-upload代码块

<el-upload :action="contractUrl" list-type="picture-card" :auto-upload="false" ref="uploadContract"
          :show-file-list="false" @error="imageContractTimeout" :on-success="handleContractSuccess"
          :on-change="uploadContractChange" :before-upload="uploadContractFun">

将图片压缩放入before-upload方法里,他会在文件上传之前执行,我们就是在这里进行图片的压缩(方法接收一个Promise回调,可研读官方文档查阅)

before-upload使用(imageConversion插件提供两个压缩方法,一种是直接压缩为kb值,一种是模糊程度压缩)

//方法一:直接将图片压缩到指定kb值
 uploadContractFun(file) {
    
    
      return new Promise((resolve, reject) => {
    
    
      //项目要求是大于5MB的图片进行压缩,可根据项目情况自行判断
        if (file.size > 5 * 1024 * 1024) {
    
    
          // console.log('压缩前', file) // 压缩到400KB
          imageConversion.compressAccurately(file, 400).then(res => {
    
    
            res = new File([res], file.name, {
    
     type: res.type, lastModified: Date.now() })
            resolve(res)
          })
        } else {
    
    
          resolve(file)
        }
      })
    }
//方法二:imageConversion.compress(file,0.6) 第二个参数过低会导致图片模糊
 uploadContractFun(file) {
    
    
      return new Promise((resolve, reject) => {
    
    
      //项目要求是大于5MB的图片进行压缩,可根据项目情况自行判断
         if (file.size > 5 * 1024 * 1024) {
    
    
          // console.log('压缩前', file) //压缩图片到0.7模糊度
          imageConversion.compress(file, 0.7).then(res => {
    
    
           res = new File([res], file.name, {
    
     type: res.type, lastModified: Date.now() })
            resolve(res)
          })
        } else {
    
    
          resolve(file);
        }
    }

注意

imageConversion内的方法压缩后返回的是blob对象,而Upload组件需要接收到File文件对象才会将压缩后的进行上传,否则不起作用,所以这里要对返回值处理成File对象
imageConversion.compress(file,0.6) 第二个参数过低会导致图片模糊

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

image-conversion 地址

https://www.npmjs.com/package/image-conversion

猜你喜欢

转载自blog.csdn.net/wangjiecsdn/article/details/126365005