问题:解决vant图片上传太大 需要进行压缩 (PS: 我写了几个方法,这里我贴出主要得代码 用//*** *** 标识 为重点)
1.图片压缩得方法
/**
* 压缩图片方法
* @param base64 ----baser64文件
* @param scale ----压缩比例 画面质量0-9,数字越小文件越小画质越差
*/
compressImg (base64, scale) {
let that = this
// 处理缩放,转换格式
// 下面的注释就不写了,就是new 一个图片,用canvas来压缩
const img = new Image()
let blob
img.src = base64
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
canvas.setAttribute('width', img.width + '')
canvas.setAttribute('height', img.height + '')
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
// 转成base64 文件
let imgType = base64.split(';')[0].split(':')[1]
base64 = canvas.toDataURL(imgType)
while (base64.length > that.maxSize) {
scale -= 0.01 // *** 每次压缩减少的比例为0.01 ***
base64 = canvas.toDataURL(imgType, scale)/*** 核心代码通过canvas去压缩 ***
}
// baser64 TO blob
const arr = base64.split(',')
const bytes = atob(arr[1])
const bytesLength = bytes.length
const u8arr = new Uint8Array(bytesLength)
for (let i = 0; i < bytes.length; i++) {
u8arr[i] = bytes.charCodeAt(i)
}
blob = new Blob([u8arr], {type: imgType})
return blob
},
2. 文件上传
updatePics (files) {
let that = this
let fileArray = []
if (files instanceof Array) { // 兼容单个图片
fileArray = files
} else {
fileArray.push(files)
}
this.filesShow.push(...fileArray) // 数组拼接
let params = new FormData() // 创建form对象
for (let i = 0; i < fileArray.length; i++) {
let fileObj = fileArray[i].file
if (fileObj.size > that.maxSize) { //*** 这边我设置得是 maxSize 为1024*1024*1 :1M ***
let File = that.compressImg(fileArray[i].content, that.scale)
params.append('file', File, fileObj.name) // *** 这边可以设置文件名称或者格式 ***
} else {
params.append('file', fileObj) // 表单提交多个file
}
}
this.$http({
url: this.$http.adornUrl('/sys/file/uploadFile'),
method: 'post',
data: params
}).then(({data}) => {
if (data && data.code === 0) {
this.fileIds.push(...data.data.fileIds)
this.filePaths.push(...data.data.filePaths)
} else {
this.$toast(data.msg)
}
})
}