简介
vue项目中,上传图片时如果图片很大,通过 image-conversion 压缩到指定大小
1. 安装依赖
npm i image-conversion --save
2. 引用
import * as imageConversion from 'image-conversion'
3. 使用
const newFile = new Promise((resolve) => {
// 压缩到500KB,这里的500就是要压缩的大小,可自定义
imageConversion.compressAccurately(file, 500).then(res => {
resolve(res)
}).finally(() => {
console.log('将图片文件压缩到了500kb')
})
})
4. 实际场景应用
<!-- 上传按钮 -->
<el-upload
action=""
class="upload"
multiple
accept=".png, .jpg, .jpeg"
:before-upload="beforeDocumentUpload"
:http-request="beforeAvatarUpload"
:on-preview="handlePictureCardPreview"
:before-remove="handlerBeforeRemove"
:file-list="pictureList"
:limit="10"
:on-exceed="handleExceed"
list-type="picture-card"
>
<i class="el-icon-plus" />
</el-upload>
<!-- 预览大图 -->
<el-dialog :visible.sync="imgVisible" :append-to-body="true">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
methods:
methods: {
// 上传前
beforeDocumentUpload(file) {
const size = file.size / 1024 / 1024
// 上传的图片大小不能超过10M
if (size > 10) {
this.$message.warning('文件大小不能超过10M!')
return false
}
const extension = this.getFileType(file)
// 只支持 png, jpg, jpeg 格式
if (!['png', 'jpg', 'jpeg'].includes(extension)) {
this.$message.warning('只能上传png、jpg、jpeg格式文件!')
return false
}
// 大于0.5M压缩成0.5M
if (size > 0.5) {
const loading = this.$loading({
lock: true,
text: '加载中'
})
// 压缩
const newFile = new Promise((resolve) => {
// 压缩到500KB,这里的500就是要压缩的大小,可自定义
imageConversion.compressAccurately(file, 500).then(res => {
resolve(res)
}).finally(() => {
loading.close()
})
})
console.log('newFIle', newFile)
return newFile
}
return true
},
// 上传
beforeAvatarUpload(file) {
const self = this
const reader = new FileReader()
reader.readAsDataURL(file.file)
reader.onload = function(e) {
// const img_base64 = e.target.result
// 自定义数组对象,传给后台的数据
self.imgBase64Array.push({
uid: file.file.uid,
base64Str: file
// base64Str: img_base64
})
}
},
// 预览大图
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url
this.imgVisible = true
},
// 删除图片
handlerBeforeRemove(file, fileList) {
this.imgBase64Array = this.imgBase64Array.filter((p) => p.uid !== file.uid)
},
handleExceed() {
this.$message.warning('图片数量最多为10张')
},
},