中英文网站建设公司,做网站怎样投放广告,集团网站建设服务公司,网站功能调研前端使用Compressor.js实现图片压缩上传
Compressor.js官方文档
安装
npm install compressorjs使用
在使用ElementUI或者其他UI框架的上传组件时#xff0c;都会有上传之前的钩子函数#xff0c;在这个函数中可以拿到原始file#xff0c;这里我用VantUI的上传做演示
a…前端使用Compressor.js实现图片压缩上传
Compressor.js官方文档
安装
npm install compressorjs使用
在使用ElementUI或者其他UI框架的上传组件时都会有上传之前的钩子函数在这个函数中可以拿到原始file这里我用VantUI的上传做演示
afterRead 函数是上传之前的钩子可以获取到原始file
templatedivvan-uploader:max-countprop.limitv-modelstate.fileList:after-readafterRead:before-readbeforeReaddeletedeleteFile//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 compressorjsconst 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 uploadingfile.message 上传中...FileUploadFun(file.file).then((res) {file.status donefile.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 doneToast(上传失败)})
}// 文件删除后触发
const deleteFile () {emit(onSuccess, state.fileList.map((i) i.url).join(,))
}// 用于返回信息
useCustomFieldValue(() state.fileList.map((item) item.url).join(,))
/script示例
Quality原始大小压缩后大小压缩比Description02.12 MB114.61 KB94.72%-0.22.12 MB349.57 KB83.90%-0.42.12 MB517.10 KB76.18%-0.62.12 MB694.99 KB67.99%推荐0.82.12 MB1.14 MB46.41%推荐12.12 MB2.12 MB0%不推荐NaN2.12 MB2.01 MB5.02%-
测试效果 可以看到压缩前的图片大小3.29M压缩后343KB 下面是前后的图片对比
原图 压缩后的图