如何验证图像尺寸? (例如:小于2MB) 我在angular4项目中使用ng2-file-input进行图片上传。
`
public onAction(event: any) {
this.resImagesSize = event.currentFiles;
for (let i = 0; i < this.resImagesSize[i].size; i++) {
if (this.resImagesSize[i].size > 2000000) {
this.toasterService.pop('error', 'Error', 'Please upload less than 2MB image');
this.resImagesSize.splice(i, 1);
} else {
this.resImages = this.resImagesSize;
}
}
}
`
编辑:这是我的多士炉服务代码 `
toasterconfig: ToasterConfig =
new ToasterConfig({
tapToDismiss: true,
timeout: 5000,
preventDuplicates: false,
positionClass: 'toast-top-center'
});
`
问题是,当我上传超过2张图片(大于2MB)时,它会显示2条消息。如何只显示一条验证消息?
答案 0 :(得分:1)
尝试这个,如果有一个或多个无效文件,它将只调用一次服务:
public onAction(event: any) {
this.resImagesSize = event.currentFiles;
let sizeValid = true;
for (let i = 0; i < this.resImagesSize[i].size; i++) {
if (this.resImagesSize[i].size > 2000000) {
sizeValid = false;
this.resImagesSize.splice(i, 1);
} else {
this.resImages = this.resImagesSize;
}}
if(!sizeValid ){
this.toasterService.pop('error', 'Error', 'Please upload less than 2MB
image');
}
}