<ks-upload
:action="uploadAction"
:headers="uploadHeader"
name="imageFile"
accept="jpg/jpeg"
list-type="picture-card"
:before-upload="beforeUpload5">
<div slot="tip" class="upload-text">图片格式为jpg/jpeg,大小不能超过3M,最多传5张</div>
</ks-upload>
// 方法:
beforeUpload5(file) {
this.loading = Loading.service({
lock: true,
text: '加载中...',
background: 'rgba(255, 255, 255, 0.5)'
})
const isJPG = file.type === 'image/jpeg' // JPG GIF PNG
const isLt2M = file.size / 1024 / 1024 > 3
if (!isJPG) {
this.$message.error('上传图片只能是jpg/jpeg格式!')
return Promise.reject()
}
if (isLt2M) {
return this.commonZipPic(file)
}
},
// 图片通用压缩提示
commonZipPic(file) {
const r = confirm(`您上传的图片大小约为${(file.size / 1048576).toFixed(2)}Mb,是否进行压缩上传?(此操作会降低图片质量)`)
if (r == true) {
const _this = this
return new Promise((resolve, reject) => {
const image = new Image()
let resultBlob = ''
image.src = URL.createObjectURL(file)
image.onload = () => {
// 调用方法获取blob格式,方法写在下边
resultBlob = _this.compressUpload(image, file)
const fs = new File([resultBlob], file.name, {
type: file.type
})
if (fs.size / 1048576 > 0.5) {
this.$message.warning('压缩后图片仍大于500kb,请您手动压缩')
reject()
}
resolve(fs)
}
image.onerror = () => {
reject()
}
})
} else {
return Promise.reject()
}
},
/* 图片压缩方法-canvas压缩 */
compressUpload(image, file) {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
// const initSize = image.src.length
const { width } = image
const { height } = image
canvas.width = width
canvas.height = height
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(image, 0, 0, width, height)
// 进行最小压缩0.1
const compressData = canvas.toDataURL(file.type || 'image/jpeg', this.imgResizeRatio)
// 压缩后调用方法进行base64转Blob,方法写在下边
const blobImg = this.dataURItoBlob(compressData)
return blobImg
},
/* base64转Blob对象 */
dataURItoBlob(data) {
let byteString
if (data.split(',')[0].indexOf('base64') >= 0) {
byteString = atob(data.split(',')[1])
} else {
byteString = unescape(data.split(',')[1])
}
const mimeString = data
.split(',')[0]
.split(':')[1]
.split(';')[0]
const ia = new Uint8Array(byteString.length)
for (let i = 0; i < byteString.length; i += 1) {
ia[i] = byteString.charCodeAt(i)
}
return new Blob([ia], { type: mimeString })
},
vue + el-upload 实现上传图片前压缩
最新推荐文章于 2024-03-29 15:14:15 发布