2016-09-30 2 views

답변

1

text.png에 있지만,하기의 질문에 대답 않습니다 true 예를 들어, 업로드 후 위의 함수에서

isImage(file: File): boolean { 
    return /^image\//.test(file.type); 
} 

는 단순히 반환 .txt- .png 파일 확장자를 변경 자바 스크립트에서 클라이언트 측 파일 유형 유효성 검사. 필요에 따라 솔루션을 쉽게 적용 할 수 있어야합니다. How to check file MIME type with javascript before upload?

0

여기에 대한 맞춤 지침이 있습니다. 다른 파일 형식에도 사용할 수 있습니다. 다만, 구성 요소에서 RegExp

import { FormControl, NG_VALIDATORS, Validator } from '@angular/forms'; 
import { Directive } from '@angular/core'; 

@Directive({ 
    selector: '[FileTypeValidator]', 
    providers: [ 
    { 
     provide: NG_VALIDATORS, useExisting: FileTypeValidator, multi: true 
    } 
    ] 
}) 
export class FileTypeValidator implements Validator { 

    static validate(c: FormControl): { [key: string]: any } { 
    if (c.value) { 
     if (c.value[0]) { 
     return FileTypeValidator.checkExtension(c); 
     }; 
    } 
    } 

    private static checkExtension(c: FormControl) { 
    let valToLower = c.value[0].name.toLowerCase(); 
    let regex = new RegExp("(.*?)\.(jpg|png|jpeg)$"); //add or remove required extensions here 
    let regexTest = regex.test(valToLower); 
    return !regexTest ? { "notSupportedFileType": true } : null; 
    } 

    validate(c: FormControl): { [key: string]: any } { 
    return FileTypeValidator.validate(c); 
    } 

} 

에 필요한 확장을 추가/제거

this.form = new FormGroup({ 
     file: new FormControl("", [FileTypeValidator.validate]) 
    }); 
관련 문제