一、安装依赖:npm install lrz --save
二、引入模块:import lrz from 'lrz'
三、使用:
1、HTML:
class="avatar-uploader" action="" :show-file-list="false" :before-upload="beforeUpload" >
2、JS:
beforeUpload(file){
this.compress(file);
},
compress(img){ //转成base64 压缩
lrz(img, {width: 640}).then(res => {
let base64Img = res.base64;
let data = {image: base64Img.slice(23)}
checkImg(data).then( res => {
if(res.ret == 0){
this.$message.success('照片合格');
let blob = this.dataURItoBlob(base64Img);
let formData = new FormData();
formData.append('file', blob, img.name);
this.uploadPhoto(formData);
} else {
this.$message.error(res.msg);
}
});
}).catch(e => {
console.log('捕获异常')
console.error(e)
})
},
// base64转成bolb对象
dataURItoBlob(base64Data) {
let byteString;
if (base64Data.split(',')[0].indexOf('base64') >= 0) {
byteString = atob(base64Data.split(',')[1]);
} else { byteString = unescape(base64Data.split(',')[1]); }
let mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
let ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], { type: mimeString });
},
uploadPhoto(file){ // 检验后 上传 调用接口
uploadImage(file).then(res => {
if (res.code == 200) {
this.$set(this.form, 'photo', res.data.absolutePath);
}
})
}