简体   繁体   中英

Angular File upload validator failed

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 class="mb-3">
            <label for="formFile" class="form-label">Pilih File</label>
            <input class="form-control" type="file" id="file" (change)="onFileChange($event)">
          </div>

Hope someone can help me. Thank you

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")
}
    ```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM