发布:2023/4/4 14:38:04作者:管理员 来源:本站 浏览次数:748
图片压缩就是采用BASE64或者用cavas将图片重新渲染绘制,整合成指定大小或质量的图片上传到服务器。本文是基于Vant的Upload组件,结合image-compressor实现
一、安装image-compressor,在组件中引入
//安装
npm install image-compressor
//引入
import ImageCompressor from 'image-compressor.js'
二、Uploader组件
<van-uploader
:after-read="afterRead"
:before-delete="deletImg"
:before-read="onRead"
:max-count="maxSize"
v-model="fileList" multiple
>
<van-icon name="plus" />
</van-uploader>
三、在图片上传前压缩图片,并转换为file格式
compressFile(file) {
return new Promise((resolve, reject) => {
new ImageCompressor(file, {
quality: 0.6, //压缩质量
checkOrientation: false, //图片翻转,默认为false
success(result) {
resolve(result);
},
error(e) {
reject()
}
})
})
},
async uploadMaterialImg(imgFile) {
let This = this
let file = await this.compressFile(imgFile)
let formData = new FormData()
formData.append('file', file)
uploadMaterial(formData).then(res => {
if (res.code == 200) {
This.fileList.push({
isImage: true,
id: res.data.ossId,
url: res.data.ossUrl,
ossNameNew: res.data.ossNameNew,
imagePath: res.data.ossUrl,
imageName: res.data.ossName,
imageType: This.materialsObj.materialsType
})
} else {
This.$toast(res.message)
}
}).catch(error => {
This.$toast(error)
})
}
关于image-compressor的文档说明,请移步:https://github.com/IronPans/img-compressor
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4