/* 图片压缩方法-canvas压缩 */
compressUpload(image, file) {
const that = this
// 默认按比例压缩
let w = that.width
let h = that.height
const scale = w / h
w = image.width || w
h = image.height || (w / scale)
// 生成canvas
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
// 创建属性节点
const anw = document.createAttribute('width')
anw.nodeValue = w
const anh = document.createAttribute('height')
anh.nodeValue = h
canvas.setAttributeNode(anw)
canvas.setAttributeNode(anh)
ctx.drawImage(image, 0, 0, w, h)
let quality = 0.9 // 图片质量 值在 0 - 1 之间 值越小 图片樾模糊
const data = canvas.toDataURL('image/jpeg', quality)
const newFile = this.dataURItoBlob(data) // base64转Blob对象
// blob转换为需要的file格式
this.newfile = new window.File([newFile], file.name, { type: file.type });
this.newfile.uid = file.uid
},
/* base64转Blob对象 */
dataURItoBlob(data, file) {
let byteString; // 去掉url的头,并转换为byte
if(data.split(',')[0].indexOf('base64') >= 0) {
byteString = atob(data.split(',')[1])
}else {
byteString = unescape(data.split(',')[1])
}
let mimeString = data
.split(',')[0]
.split(':')[1]
.split(';')[0];
// 处理异常,将ascii码小于0的转换为大于0
let 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})
},
fileUpload(newfile) {
const loading = this.$loading({
lock: true,
text: '正在上传中...',
spinner: 'el-icon-loading',
background: 'rgba(255, 255, 255, 0.4)'
});
let obj = newfile.name
let index = obj.lastIndexOf(".")
let outputType = obj.substring(index, obj.length)
let size = newfile.size
let fileTime = this.M().format('YYYYMMDD')
let uuid = getFileNameUUID()
put(`${this.fileName}/${fileTime}/${uuid}${outputType}`, newfile).then((res) => {
try {
if(res.res.status == 200){
this.progressNum = progress
var currentPic
if(size >= 100*1024 ){
currentPic = `${res.res.requestUrls[0].split("?")[0]}?x-oss-process=style/${this.watermark}`
}else{
currentPic = `${res.res.requestUrls[0]}?x-oss-process=style/${this.watermark}`
}
this.uploadList.push({
name: res.name,
url: currentPic,
hotpoint: 0
})
if (this.uploadList.length === this.files.length) {
loading.close()
const files = [] // 需要上传的数组
this.uploadList.forEach(data => {
files.push(data)
})
this.$emit('imgupload', files)
}
loading.close()
}
} catch (e) {
loading.close()
}
})
},
// 判断图片大小-进行压缩-上传服务器
uploadFunc(param){
let file = param.file
let MBsize = 1
let isLt2M = file.size / 1024 / 1024 > MBsize; // 判定图片大小是否大于 *** MB
if (isLt2M) { // 大于规定*M 则走压缩逻辑
let image = new Image()
image.src = URL.createObjectURL(file);
image.onload = () => {
this.compressUpload(image, file) // 调用方法获取处理后的图片文件
const { newfile } = this
this.fileUpload(newfile)
}
} else { // 否则直接上传 不走压缩
this.fileUpload(file)
}
},
<el-upload
:http-request="uploadFunc"
:multiple="multiple"
:limit="limit"
:file-list.sync="uploadList">
</el-upload>