Friday 19 January 2018

File upload validation - Angular

AngularFile UploadValidation

In this article we will be discussing about validating a file/image from client side before uploading. In my previous articles I have covered file upload and showing a preview image while uploading, now let us check the validation part.


import { Component } from '@angular/core';
import { commonService } from './services/commonService'

    selector: 'app-root',
    template: '<div>'
        + '<input type="file" (change)="upload($event)">'
        + '</div>',

export class AppComponent {
    constructor(private _service: commonService) { }

    upload(event: any) {
        let 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));
            response => console.log(response),
            error => console.log(error)


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

Here we are taking the file/image extension and validating before uploading to backend. Similar way you can check other extensions as well.

if (ext.toLowerCase() == 'war')
if (ext.toLowerCase() == 'csv')
if (ext.toLowerCase() == 'jpeg')

We are done. In this article we have discussed about validating a file/image before uploading to backend.

Angular 2+Angular 4/5File UploadValidation

Related Info

1. File/Image upload validation- Angular

2. File/Image upload and send data to backend

3. Show preview image while uploading file/image

4. Rating star component - Angular

5. Date filtering and formatting - Angular


  1. how to store file to local directory?

  2. Any way to also validate for malicious file?