简体   繁体   English

角度 7 中的文件验证

[英]File validation in angular 7

How to validate file like file size and file type before it upload to the server.如何在文件上传到服务器之前验证文件大小和文件类型。 And how to use this validation with reactive form or template driven approach.以及如何将这种验证与反应式表单或模板驱动的方法一起使用。

By default, reactive or template driven forms do not support files, so you need to create a custom ControlValueAccessor which wraps the File variable.默认情况下,响应式或模板驱动的表单不支持文件,因此您需要创建一个自定义ControlValueAccessor来包装 File 变量。 That's exactly what is done here .这正是这里所做的。

Here is the relevant part:这是相关部分:

@Component({
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: FileUploadComponent,
      multi: true
    }
  ]
})
export class FileUploadComponent implements ControlValueAccessor {
  @Input() progress;
  onChange: Function;
  private file: File | null = null;

  @HostListener('change', ['$event.target.files']) emitFiles( event: FileList ) {
    const file = event && event.item(0);
    this.onChange(file);
    this.file = file;
  }

  constructor( private host: ElementRef<HTMLInputElement> ) {
  }

  writeValue( value: null ) {
    // clear file input
    this.host.nativeElement.value = '';
    this.file = null;
  }

  registerOnChange( fn: Function ) {
    this.onChange = fn;
  }

  registerOnTouched( fn: Function ) {
  }

}

If you need any validation then you could implement it inside this custom component.如果您需要任何验证,那么您可以在此自定义组件中实现它。 Just grab a reference of the NgControl by injecting it and call setErrors accordingly.只需通过注入获取 NgControl 的引用并相应地调用setErrors 即可

You can get the change event and check for the file size and type您可以获取更改事件并检查文件大小和类型

In your ts file have this method.在你的 ts 文件中有这个方法。

readFile(fileEvent: HTMLInputEvent) {
   const file: File = fileEvent.target.files[0];
   console.log('size', file.size);
   console.log('type', file.type);
}

And in your html handle onchange event并在您的 html 处理 onchange 事件

<input (change)="readFile($event)" type="file" />

I'm not sure if my answer is still relevant.我不确定我的回答是否仍然相关。 but after some digging and messing around I came up with this solution (taken from my own project).但是经过一番挖掘和混乱之后,我想出了这个解决方案(取自我自己的项目)。 Please keep in mind that I'm using multiple files upload.请记住,我正在使用多个文件上传。

HTML: HTML:

<input type="file" multiple (change)="onFilePicked($event.target.files)" />

Component: Assuming you are using and have created a formbuilder组件:假设您正在使用并创建了一个表单构建器

this.formBuilder= this.fb.group({
  files: ['', [checkFileType]],
  //other fields
 })

 //custom validation
function checkFileType(control: AbstractControl): { [key: string]: any } | null {
    const files: File[] = control.value;
    let errors: string[] = [];

   if (files.length >= 1 ) {
       for (let index = 0; index < files.length; index++) {
           //Use a type list here to check for your types for example "image/jpeg"
           if (files[index].type === '') {                 
               errors.push(`${files[index].name} has an invalid type of unknown\n`);
           }
       }

       return  errors.length >= 1 ? { invalid_type: errors } : null;           
   }
   return null;  // no file, can be capture by "Required" validation 
}

To catch the error in your HTML:要捕获 HTML 中的错误:

<div *ngIf="files.errors">
    <div class="text-danger" *ngFor="let typeError of files.errors.invalid_type">
        <span>- {{ typeError }}.</span>
    </div>
</div>

This solution did it for me.这个解决方案为我做到了。 I hope it helps you as well.我希望它也能帮助你。

example output (greetings from Belgium :D)示例输出(来自比利时的问候:D) 在此处输入图片说明

The problem is pretty much solvable with HTML itself.这个问题几乎可以用 HTML 本身解决。 No angular related stuff needed.不需要角度相关的东西。

 <form action="/action_page.php">
     <input type="file" name="pic" accept="image/*">
     <input type="submit">
 </form> 

The accept property can be used as follows:可以按如下方式使用 accept 属性:

<input accept="file_extension|audio/*|video/*|image/*|media_type"> 

The accept parameters are explained as follows:接受参数解释如下:

  • file_extension Specify the file extension(s) (eg: .gif, .jpg, .png, .doc) the user can pick from file_extension指定用户可以选择的文件扩展名(例如:.gif、.jpg、.png、.doc)
  • audio/* The user can pick all sound files audio/*用户可以选择所有的声音文件
  • video/* The user can pick all video files video/*用户可以选择所有视频文件
  • image/* The user can pick all image files image/*用户可以选取所有图像文件
  • media_type A valid media type, with no parameters. media_type一个有效的媒体类型,没有参数。 Look at IANA Media Types for a complete list of standard media types查看IANA 媒体类型以获取标准媒体类型的完整列表

Hope this helps :)希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM