简体   繁体   English

如何强制用户仅上传 Angular 中的特定文件类型

[英]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.

相关问题 如何在Angular的服务器上仅上传一个文件? - How to upload only one file on a server in Angular? 只允许angular-file-upload模块中的特定文件扩展名可单击 - Only allow specific file extensions in angular-file-upload module to be clickable 如何将文件限制为仅在Angular文件上传中以UTF-8编码? - How to restrict files to UTF-8 encoded only in Angular file upload? 限制 Dropzone 仅上传特定类型的文件 - Restrict Dropzone to upload only specific type of files 如何使用php在Yii框架中仅上传pdf类型文件 - How to upload only pdf type file in Yii framework using php 如何通过javascript验证输入(type =“file”)仅用于上传图像? - how to validation the input (type=“file”) by javascript for upload images only? 仅以特定格式上传文件的条件 - a condition for upload file only with specific format 检查 PrimeNG 和 Angular 中的文件上传类型 - Check file upload type in PrimeNG and Angular 可以在此特定功能上下文中强制执行类型吗? - Possible to enforce type in this specific functional context? 如何强制用户仅将文件上传到Firebase中特定文件的某些节点。 - How to enforce users to only upload files to certain nodes for particular files in Firebase.
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM