检查 PrimeNG 中的文件上传类型和 Angular

Check file upload type in PrimeNG and Angular

我正在尝试限制用户可以上传的文件类型。我只能允许 pdf 和 doc。 我的HTML有以下

<input #pdfUploadID type="file" id="fileUploadID" formControlName="fileUploadID" (change)="handleFileInput($event.target.files, 'id')" accept=".pdf,.doc">

单独执行此操作仍然允许用户更改浏览器弹出窗口中允许的类型 window,如下所示

所以我有自定义代码来检查用户上传后的文件类型,如下所示

if (this.fileToUploadID.type !== 'application/pdf') {
   this.isPDFId = false;
} else { this.isPDFId = true; }

我的问题是,当我尝试像这样向 if 语句添加更多类型时,出现以下错误

This condition will always return 'true' since the types '"application/pdf"' and '"application/msword"' have no overlap.

 if ((this.fileToUploadID.type !== 'application/pdf')||(this.fileToUploadID.type !== 'application/msword')) {
    console.log("file type: "+this.fileToUploadID.type);
    this.isPDFId = false;
 } else { this.isPDFId = true; }

我应该添加什么想法?

只需将您的 if 语句替换为以下内容:

this.isPDFId = this.fileToUploadID.type === 'application/pdf' && this.fileToUploadId.type === 'application/msword' ? true : false;

fileTypes: any = [
   {type: 'application/msword', name: 'Doc'},
   {type: 'application/pdf', name: 'Pdf'}
];
fileType: string;

handleFileInput(event){
  const files = event.target.files;
  const mimeType = files[0].type;
  
  if(mimeType !== this.fileType) {
    alert(`please select a ${this.fileType} file`);
  }
  
}
<input type="file" id="fileUploadID" (change)="handleFileInput($event)" accept=".pdf,.doc"> 

<select [(ngModel)]='fileType'>
  <options *ngFor="let type of fileTypes">{{type.name}}</options>
</select>

我已经查看了有关 File 接口的 PrimeNG 文档,看起来 File.type 被键入为字符串。看起来你可能会为那个 属性 分配不同的类型值,但是如果没有完整的组件预览就很难说。

比较字符串与数字时出现类似错误:

value === 1 ? true : false

This condition will always return 'false' since the types 'string' and '1' have no overlap.ts(2367)

将上面更改为下面已删除的错误:

value === '1' ? true : false

如果您没有找到问题的原因,请尝试在比较时使用 .toString() 将值转换为字符串:

this.fileToUploadID.type.toString() === 'application/pdf' && this.fileToUploadId.type.toString() === 'application/msword' ? true : false;

然而,这也应该通过使用 @StefanN 建议的非严格比较运算符来解决。