【问题标题】:Check file upload type in PrimeNG and Angular检查 PrimeNG 和 Angular 中的文件上传类型
【发布时间】:2019-11-08 19:55:13
【问题描述】:

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

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

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

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

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

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

此条件将始终返回“真”,因为类型 '"application/pdf"' 和 '"application/msword"' 没有重叠。

 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; }

有什么我应该添加的想法吗?

【问题讨论】:

标签: javascript angular primeng


【解决方案1】:

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

在比较字符串和数字时遇到了类似的错误:

value === 1 ? true : false

此条件将始终返回 'false',因为类型 'string' 和 '1' 没有重叠。ts(2367)

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

value === '1' ? true : false

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

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我的编辑器This condition will always return 'false' since the types '"application/pdf"' and '"application/msword"' have no overlap.
    • 我明白了。你知道this.fileToUploadId.type是什么类型吗?否则,您可以尝试使用== 代替===
    • 它是文件类型,声明如下fileToUploadID: File = null; 将其更改为“==”没有区别
    【解决方案3】:

    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>

    【讨论】:

    • 实际上与问题的上下文不同。该示例也不起作用。
    猜你喜欢
    • 2015-07-21
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 2014-02-20
    • 2013-01-04
    • 1970-01-01
    相关资源
    最近更新 更多