我嘗試使用 Angular 在前端為上傳的檔案構建驗證器。我的驗證器很簡單。我將函式onFileChange(event)放在檔案輸入表單上,以從將要上傳的檔案中獲取屬性。然后我嘗試過濾它。只可以上傳 png、jpg、jpeg 和 pdf 檔案。但它沒有按預期作業。當我上傳 png 檔案時,它會顯示警報彈出視窗。這是我onFileChange(event的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)
}
}
這是我的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>
希望可以有人幫幫我。謝謝
uj5u.com熱心網友回復:
問題是您正在使用||而不是&&
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")
}
}
}
我們的你可以做相反的事情:
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")
}
```
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/431915.html
標籤:javascript html css 有角度的 打字稿
