Closed wisetc closed 5 years ago
class IdcardUploader extends Component {
// ...
minKB = 10;
maxMB = 8;
normalMB = 2;
async handleChange(e) {
const files = e.target.files;
if (!files.length) return;
const file = files[0];
const reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
})(this.previewEl);
console.log({ file });
const fileSize = file.size;
this.setState({
fileSize,
});
if (fileSize > this.maxMB * oneMB) {
feedback.error(
`您上传的图片的体积大于 ${this.maxMB}M,无法为您上传该图片`,
() => {
this.setState({
fileSize: null,
});
console.log('uploader canceled - file to large.');
}
);
return;
} else if (fileSize < this.minKB * oneKB) {
feedback.error(`该图片非正常图片,请确认后再重新选择`, () => {
this.setState({
fileSize: null,
});
console.log('uploader canceled - file to small.');
});
return;
}
let compressedFile = file;
const closeLoading = feedback.loading();
if (fileSize > this.normalMB * oneMB) {
try {
compressedFile = await imageCompression(file, this.normalMB); // maxSizeMB, maxWidthOrHeight are optional
console.log(
`compressedFile size ${compressedFile.size / 1024 / 1024} MB`
); // smaller than maxSizeMB
} catch (error) {
console.log(error);
}
}
uploadFileList([compressedFile])
.then(res => {
reader.readAsDataURL(compressedFile);
typeof this.props.uploadSuccess === 'function' &&
this.props.uploadSuccess(res.map(item => item.url), this.props.type);
})
.finally(() => {
closeLoading();
});
}
// ...
}
修改
4, 5, 2M改0.8M。
补充,
上述优化项开发时间1天,体验效果及测试时间1天,确认无误立即发布。
最终,图片压缩模块,从
browser-image-compression
和compressorjs
中,选择了前者,browser-image-compression
版本为0.0.3
。