1

How to validate image size? (ex: less than 2MB) I'm using ng2-file-input for image uploading in my angular4 project.

`

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;
}
}
}

`

Edit: here is my toasterService code `

toasterconfig: ToasterConfig =
    new ToasterConfig({
      tapToDismiss: true,
      timeout: 5000,
      preventDuplicates: false,
      positionClass: 'toast-top-center'
    });

`

problem is when i upload more than 2 images(bigger than 2MB) it display 2 messages. How to display only one validation message ?

6
  • Can you provide the code from toasterService, my advice is to add logic to your service that only one error message is shown at a time Commented Nov 10, 2017 at 8:40
  • @JasperSeinhorst here is my code ` toasterconfig: ToasterConfig = new ToasterConfig({ tapToDismiss: true, timeout: 5000, preventDuplicates: false, positionClass: 'toast-top-center' });` Commented Nov 10, 2017 at 8:44
  • Please add it to the question Commented Nov 10, 2017 at 8:45
  • @JasperSeinhorst done Commented Nov 10, 2017 at 8:50
  • preventDuplicates: false, set this on true, and it will work as expected Commented Nov 10, 2017 at 8:52

1 Answer 1

1

try this, that will call the service only one time, if there is one of more invalid files:

   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');
    }
 }
Sign up to request clarification or add additional context in comments.

3 Comments

And what if toy upload a too big file on the seconds try? The error isn't visible.
i think it works good for multiple file select, if there will be one or more invalid files the service is called but only once, can you explain more your case please
did you get an error? i forget ; after sizeValid = false it should be sizeValid = false;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.