Home > front end >  Angular File upload validator failed
Angular File upload validator failed

Time:02-24

I tried to build validator for uploaded file in front end using angular. My validator is simple. I put function onFileChange(event) on file input form to get properties from file that would be uploaded. Then I tried to filter it. Just png, jpg, jpeg and pdf file can be uploaded. But it did not work as expected. When I upload png file, it shows alert popup. This is my onFileChange(event on component.ts

onFileChange(event:any){
    if(event.target.files.length > 0){
      this.selectedFile = event.target.files[0]
      if(this.selectedFile.type != "image/png" || this.selectedFile.type != "image/jpg" || this.selectedFile.type != "image/jpeg" || this.selectedFile.type != "application/pdf" ){
        alert("File type must be png,jpg,jpeg and pdf")
      }
      console.log(this.selectedFile)
    }
  }

And this is my html file

          <div >
            <label for="formFile" >Pilih File</label>
            <input  type="file" id="file" (change)="onFileChange($event)">
          </div>

Hope someone can help me. Thank you

CodePudding user response:

The problem is that you are using || instead of &&

onFileChange(event:any){
  if(event.target.files.length > 0){
    this.selectedFile = event.target.files?[0];
    if(this.selectedFile){
      // no file selected
      return;
    }
    if(this.selectedFile.type !== "image/png" &&
    this.selectedFile.type !== "image/jpg" &&
    this.selectedFile.type !== "image/jpeg" &&
    this.selectedFile.type !== "application/pdf" ){
      alert("File type must be png, jpg, jpeg or pdf")
    }
  }
}

our you could do the opposite:

if(this.selectedFile.type === "image/png" ||
    this.selectedFile.type === "image/jpg" ||
    this.selectedFile.type === "image/jpeg" ||
    this.selectedFile.type === "application/pdf" ){
    // the file is OK
} else {
    alert("File type must be png, jpg, jpeg or pdf")
}
    ```
  • Related