【问题标题】:How to enforce user to upload only specific file type in Angular如何强制用户在 Angular 中仅上传特定的文件类型
【发布时间】:2020-06-02 15:08:49
【问题描述】:

我想强制用户在 Angular 7 中仅上传 pdf 文件,这是我的代码的一部分。当我单击页面上的“选择文件”按钮时,它会带来“PDF 文件”,但也会带来 ”所有文件” 我想通过 javascript 函数或 typescript 函数强制用户帮助我:)

打字稿

  filesP2: File[] = [];
  lastInvalidsP2: any;
  sendableFormDataP2: FormData;
  httpEmitter: Subscription;
  httpEvent: HttpEvent<{}>;
  maxSize: any;
  lastFileAt: Date;
  isBelgeVisible: boolean = false;
  uploadedBelgeId: number = null;

HTML

<input style="margin: 0 auto;" ngfSelect type="file" [(files)]="filesP2" accept=".pdf" [maxSize]="maxSize" [(lastInvalids)]="lastInvalidsP2" (filesChange)="lastFileAt=getDate()"/>

<ngfFormData [files]="filesP2" postName="file" [(FormData)]="sendableFormDataP2"></ngfFormData>

【问题讨论】:

  • 这是不可能的,使用 'accept' 是尽可能接近的。选择文件后,您应该检查它是否是正确的文件类型。即使在那之后你也应该做一些后端验证
  • 没关系,但即使用户选择“所有文件”选项并想要上传另一种文件类型,如“.txt 或 .docx”等。必须有“这不是 PDF 文件”之类的错误我只是想在后端运行它但是如何?
  • 您可以在.的基础上拆分文件名,然后检查文件扩展名是否为pdf,并可以决定进一步的操作。
  • @FarhatZaman 你能举个例子吗?
  • 您正在使用哪个 npm 包进行文件上传。能给我个链接吗?

标签: javascript html angular typescript


【解决方案1】:

如果您使用的是响应式表单,您可以创建自定义验证器

import {
  FormControl
} from '@angular/forms';

export function requiredFileType(expectedFormats: string[]) {
  return function(control: FormControl) {
    const files = control.value;
    if (files) {
      const hasOtherType = files.some(file => {
        const splitParts = file.name.split('.');
        const extension = splitParts[splitParts.length - 1].toLowerCase();

        return 'pdf' != extension.toLowerCase();
      });
      if (hasOtherType) {
        return {
          requiredFileType: 'Wrong file type. Only pdf type supported.'
        };
      }
    }


    return null;
  };
}

//usage in angular forms
File: new FormControl({
  value: null,
  disabled: true
}, [Validators.required, requiredFileType(['xlsx', 'xlsm'])])

【讨论】:

    猜你喜欢
    • 2016-10-21
    • 2018-06-15
    • 2018-11-19
    • 1970-01-01
    • 2020-08-09
    • 2022-11-28
    • 2021-10-14
    • 1970-01-01
    • 2021-05-16
    相关资源
    最近更新 更多