Traté de construir un validador para el archivo cargado en el front-end usando angular. Mi validador es simple. Puse la función onFileChange(event) en el formulario de entrada de archivos para obtener las propiedades del archivo que se cargaría. Luego traté de filtrarlo. Solo se pueden cargar archivos png, jpg, jpeg y pdf. Pero no funcionó como se esperaba. Cuando subo un archivo png, muestra una ventana emergente de alerta. Este es mi onFileChange(event en 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) } } Y este es mi archivo html
<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>Espero que alguien pueda ayudarme. Gracias
El problema es que estás usando || en lugar de &&
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") } } }nuestro podrías hacer lo contrario:
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") } ```