简体   繁体   中英

File upload validation in angular 4

What is the best way to validate file type when trying to upload file in angular 4 form. Is there any easy way to achieve this?

Yes you can validate from client side

sample code

 upload(event: any) {
        let files = event.target.files;
        //check file is valid
        if (!this.validateFile(files[0].name)) {
            console.log('Selected file format is not supported');
            return false;
        }

        let fData: FormData = new FormData;

        for (var i = 0; i < files.length; i++) {
            fData.append("file", files[i]);
        }
        var _data = {
            filename: 'Sample File',
            id: '0001'
        }

        fData.append("data", JSON.stringify(_data));
        this._service.uploadFile(fData).subscribe(
            response => console.log(response),
            error => console.log(error)
        )
    }

validation

validateFile(name: String) {
    var ext = name.substring(name.lastIndexOf('.') + 1);
    if (ext.toLowerCase() == 'war') {
        return true;
    }
    else {
        return false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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