``
react项目
dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
// 图片压缩
getsmallpic(file){
return new Promise((resolve,reject)=>{
//对图片进行压缩
const reader = new FileReader()
const image = new Image()
image.onload = (imageEvent) => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d'); //画布上绘制的类型为2D
const width = image.width * 0.5
const height = image.height * 0.5
canvas.width = width;
canvas.height = height;
context.clearRect(0, 0, width, height);// 清空给定矩形内的指定像素。
context.drawImage(image, 0, 0, width, height); //在画布上定位图像,并规定图像的宽度和高度
const dataUrl = canvas.toDataURL(file.type);
const blobData = this.dataURLtoFile(dataUrl,file.name);
if(blobData){
if(blobData.size /1024 < 400){
Object.assign(blobData,{uid:blobData.lastModified});
const windowURL = window.URL || window.webkitURL;//实现预览
resolve(blobData)
this.setState({
imgSrc:windowURL.createObjectURL(blobData),
class:1
})
this.setState({
imgArr:blobData
})
}else{
this.getsmallpic(blobData)
}
}else{
reject()
}
}
reader.onload = (e => { image.src = e.target.result; });
reader.readAsDataURL(file);
})
}
```humanChange(e){ //文件上传事件
const windowURL = window.URL || window.webkitURL;//实现预览
const file = document.getElementById('faceHuman').files[0];
console.log(file.size/1024+'kb')
const isLt400K = file.size /1024 < 400;
if(!isLt400K){
// let newfile =await getsmallpic(file)
return this.getsmallpic(file)
}else{
this.setState({
imgSrc:windowURL.createObjectURL(file),
class:1
})
this.setState({
imgArr:file
})
}
}