[英]How to enforce user to upload only specific file type in Angular
I want to enforce user to upload only pdf files in Angular 7 this is part of my code.When i click the button which is "Select File" at the page it brings "PDF File" but also brings "All Files" i want to enforce user by javascript function or typescript function help me please:)我想强制用户在 Angular 7 中仅上传 pdf 文件,这是我的代码的一部分。当我单击页面上的“选择文件”按钮时,它会带来“PDF 文件”,但也会带来“所有文件”我想要通过 javascript function 或 typescript ZC1C425268E68385D1AB5074C17A94F1 强制用户:
Typescript Typescript
filesP2: File[] = [];
lastInvalidsP2: any;
sendableFormDataP2: FormData;
httpEmitter: Subscription;
httpEvent: HttpEvent<{}>;
maxSize: any;
lastFileAt: Date;
isBelgeVisible: boolean = false;
uploadedBelgeId: number = null;
HTML 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>
If you are using reactive forms you can create custom validator如果您使用的是反应式 forms 您可以创建自定义验证器
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'])])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.