前端使用Compressor.js实现图片压缩上传
Compressor.js官方文档
安装
npm install compressorjs
使用
在使用ElementUI或者其他UI框架的上传组件时,都会有上传之前的钩子函数,在这个函数中可以拿到原始file,这里我用VantUI的上传做演示
afterRead 函数是上传之前的钩子,可以获取到原始file
<template><div><van-uploader:max-count="prop.limit"v-model="state.fileList":after-read="afterRead":before-read="beforeRead"@delete="deleteFile"/></div>
</template>
<script setup>
import { reactive, defineEmits, defineProps, watch } from 'vue'
import { FileUploadFun } from '@/api/index.js'
import { useCustomFieldValue } from '@vant/use'
import { Toast } from 'vant'
import Compressor from 'compressorjs'const prop = defineProps({url: {type: String,default: '',},limit: {type: Number,default: 5,},
})
const emit = defineEmits(['onSuccess'])
const state = reactive({fileList: [],
})watch(() => prop.url,() => {if (prop.url) {state.fileList = []prop.url.split(',').forEach((item) => {state.fileList.push({url: item,})})}}
)// 文件上传之前对图片进行压缩
const beforeRead = (file) => {return new Promise((resolve, reject) => {new Compressor(file, {// 压缩质量,0-1之间。数字越小,压缩比越高quality: 0.2,success(result) {// 默认返回result是blob类型的文件,可以转成file并返回,交给afterRead钩子进行上传let newFile = new File([result], file.name, { type: file.type })resolve(newFile)},error(err) {reject(err)},})})
}// 文件上传后触发
const afterRead = (file) => {file.status = 'uploading'file.message = '上传中...'FileUploadFun(file.file).then((res) => {file.status = 'done'file.message = '上传成功'let urls = state.fileList.map((i) => i.url)urls.pop()urls.push(res.data.url)// 通知外界上传成功emit('onSuccess', urls.join(','))}).catch(() => {state.fileList.pop()file.status = 'done'Toast('上传失败')})
}// 文件删除后触发
const deleteFile = () => {emit('onSuccess', state.fileList.map((i) => i.url).join(','))
}// 用于返回信息
useCustomFieldValue(() => state.fileList.map((item) => item.url).join(','))
</script>
示例
Quality | 原始大小 | 压缩后大小 | 压缩比 | Description |
---|---|---|---|---|
0 | 2.12 MB | 114.61 KB | 94.72% | - |
0.2 | 2.12 MB | 349.57 KB | 83.90% | - |
0.4 | 2.12 MB | 517.10 KB | 76.18% | - |
0.6 | 2.12 MB | 694.99 KB | 67.99% | 推荐 |
0.8 | 2.12 MB | 1.14 MB | 46.41% | 推荐 |
1 | 2.12 MB | 2.12 MB | 0% | 不推荐 |
NaN | 2.12 MB | 2.01 MB | 5.02% | - |
测试效果
可以看到压缩前的图片大小3.29M,压缩后343KB
下面是前后的图片对比
原图
压缩后的图