在做的项目(前端React+后端Django Rest)中,前端Form中有多个File Input,用户可选择上传图片。测试中发现,如果用户选择多个图片且图片较大,上传往往崩溃,这很可能是因为我的服务器配置太低。项目对图片尺寸没有过高要求,因此增加上传前压缩图片功能,既节省带宽,又缩短用户等待时间。一番摸索后,代码如下,贴在这儿一是备忘,二是帮助万一遇到同样问题的同学。
render():
render(){
return(
...
<label>Image1
<input type="file" id="img1" on Change={this.handleChange} />
</label>
<br/>
<img id="img1_preview" src="" height="100" />
<label>Image2
<input type="file" id="img2" on Change={this.handleChange} />
</label>
<img id="img2_preview" src="" height="100" />
...
)
}
function():
...
handleChange(event) {
...
/* handle all image input change */
if (event.target.id.includes('img')) {
var field = event.target.id;
var preview = document.getElementById(field + '_preview');
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function(readerEvent) {
var image = new Image();
image.onload = function(imageEvent) {
var canvas = document.createElement('canvas');
var max_size = 800; /* max size */
var width = image.width, height = image.height;
/* alter image size */
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
/* draw image on canvas */
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
/* canvas to blob */
canvas.toBlob(function(blob){
this.setState({[field]:blob});
var reader1 = new FileReader();
reader1.addEventListener("load",function(){
preview.src = dataUrl;
}, false);
reader1.readAsDataURL(blob);
});
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
}
参考stackoverflow上的这个帖子。