Validation in EJ2 TypeScript File Upload

08 Sep 202618 minutes to read

The uploader component validates the selected files’ size and extension using the allowedExtensions, minFileSize and maxFileSize properties. The files can be validated before uploading to the server and can be ignored during upload. Also, you can validate the files by setting the HTML attributes on the original input element. The validation process also occurs when files are dragged and dropped.

File type

You can allow only specific files to be uploaded using the allowedExtensions property. The extensions can be specified as a comma-separated list (for example, allowedExtensions: '.jpg,.png'). The uploader component filters the selected or dropped files to match against the specified file types and processes the upload operation. Validation also occurs when you specify a value for the accept attribute on the original input element (for example, <input type="file" accept=".jpg,.png" />).

import { Uploader } from '@syncfusion/ej2-inputs';

// initialize Uploader component
    let uploadObj: Uploader = new Uploader({
        asyncSettings: {
            saveUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Save',
            removeUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Remove'
        },
        allowedExtensions: '.jpg,.png'
    });
    uploadObj.appendTo('#fileupload');
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Essential JS 2 Uploader</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 Uploader Component" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-inputs/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-buttons/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
        <div id='container'>
            <input type="file" id="fileupload" name="UploadFiles"/>
        </div>
    </div>
</body>
</html>
#container {
  visibility: hidden;
}

#loader {
  color: #008cff;
  font-family: 'Helvetica Neue','calibiri';
  font-size: 14px;
  height: 40px;
  left: 45%;
  position: absolute;
  top: 45%;
  width: 30%;
}

File size

The uploader component allows you to validate the files based on their size. The validation helps to restrict uploading large files or empty files to the server. The size is represented in bytes. By default, the uploader component allows you to upload a minimum file size of 0 bytes and a maximum file size of 28.4 MB using the minFileSize and maxFileSize properties (for example, maxFileSize: 1000000).

import { Uploader  } from '@syncfusion/ej2-inputs';

    // Initialize the uploader component
    let uploadObj: Uploader = new Uploader({
        asyncSettings: {
            saveUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Save',
        removeUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Remove'
        },
        minFileSize: 10000,
        maxFileSize: 1500000
    });
    uploadObj.appendTo('#fileupload');
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Essential JS 2 Uploader</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 Uploader Component" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-inputs/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-buttons/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
        <div id='container'>
            <input type="file" id="fileupload" name="UploadFiles"/>
        </div>
    </div>
</body>
</html>
#container {
  visibility: hidden;
}

#loader {
  color: #008cff;
  font-family: 'Helvetica Neue','calibiri';
  font-size: 14px;
  height: 40px;
  left: 45%;
  position: absolute;
  top: 45%;
  width: 30%;
}

Maximum files count

You can restrict the maximum number of files that can be uploaded using the selected event. In the selected event arguments, you can get the currently selected files’ details using getFilesData(). You can modify the files’ details and assign the modified file list to eventArgs.modifiedFilesData.

import { enableRipple } from '@syncfusion/ej2-base';
import { Uploader, FileInfo, SelectedEventArgs } from '@syncfusion/ej2-inputs';
import { detach } from '@syncfusion/ej2-base';
import { createSpinner, showSpinner, hideSpinner } from '@syncfusion/ej2-popups';

enableRipple(true);
 let dropElement: HTMLElement = document.getElementsByClassName('control-fluid')[0] as HTMLElement;

    // Initialize the control with file validation
    let uploadObj: Uploader = new Uploader({
        autoUpload: false,
        minFileSize: 10000,
        allowedExtensions: '.doc, .docx, .xls, .xlsx',
        asyncSettings: {
            saveUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Save',
            removeUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Remove'
        },
        selected: onFileSelected,
        success: onUploadSuccess,
        dropArea: dropElement
    });
    uploadObj.appendTo('#validation');

    function onFileSelected(args : SelectedEventArgs) : void {
        // Filter the 5 files only to showcase
        args.filesData.splice(5);
        let filesData : FileInfo[] = uploadObj.getFilesData();
        let allFiles : FileInfo[] = filesData.concat(args.filesData);
        if (allFiles.length > 5) {
            for (let i : number = 0; i < allFiles.length; i++) {
                if (allFiles.length > 5) {
                    allFiles.shift();
                }
            }
            args.filesData = allFiles;
            // set the modified custom data
            args.modifiedFilesData = args.filesData;
        }
        args.isModified = true;
    }

    function onUploadSuccess(args: any): void {
        let li: HTMLElement = this.uploadWrapper.querySelector('[data-file-name="' + args.file.name + '"]');
        if (args.operation === 'upload') {
            (li.querySelector('.e-file-delete-btn') as HTMLElement).onclick = () => {
                generateSpinner(this.uploadWrapper);
            };
            (li.querySelector('.e-file-delete-btn') as HTMLElement).onkeydown = (e: any) => {
                if (e.keyCode === 13) {
                    generateSpinner(e.target.closest('.e-upload'));
                }
            };
        } else {
            hideSpinner(this.uploadWrapper);
            detach(this.uploadWrapper.querySelector('.e-spinner-pane'));
        }
    }

    function generateSpinner(targetElement: HTMLElement): void {
        createSpinner({ target: targetElement, width: '25px' });
        showSpinner(targetElement);
    }
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Essential JS 2 Uploader</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 Uploader Component" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-inputs/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-buttons/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
        <div id='container'>
            <input type="file" id="validation" name="UploadFiles"/>
        </div>
    </div>
</body>
</html>
#container {
  visibility: hidden;
}

#loader {
  color: #008cff;
  font-family: 'Helvetica Neue','calibiri';
  font-size: 14px;
  height: 40px;
  left: 45%;
  position: absolute;
  top: 45%;
  width: 30%;
}

Duplicate files

You can validate duplicate files before uploading to the server using the selected event. Compare the selected files with the existing files’ data (for example, by name and size) and filter the file list by removing the duplicate files.

import { enableRipple } from '@syncfusion/ej2-base';
enableRipple(true);
import { Uploader, FileInfo } from '@syncfusion/ej2-inputs';
import { detach, isNullOrUndefined } from '@syncfusion/ej2-base';

    // Initialize the control with file validation
     let uploadObj: Uploader = new Uploader({
        autoUpload: false,
        asyncSettings: {
            saveUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Save',
            removeUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Remove'
        },
        selected: onFileSelect,
    });
    uploadObj.appendTo('#validation');

  function onFileSelect(args : any) {
    let existingFiles: FileInfo[] = this.getFilesData();
    for (let i: number = 0; i < args.filesData.length; i++) {
        for(let j: number = 0; j < existingFiles.length; j++) {
            if (!isNullOrUndefined(args.filesData[i])) {
                if (existingFiles[j].name == args.filesData[i].name) {
                    args.filesData.splice(i, 1);
                }
            }
        }
    }
    existingFiles = existingFiles.concat(args.filesData);
    args.modifiedFilesData = existingFiles;
    args.isModified = true;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Essential JS 2 Uploader</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 Uploader Component" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-inputs/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/34.2.2/ej2-buttons/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
        <div id='container'>
            <input type="file" id="validation" name="UploadFiles"/>
        </div>
    </div>
</body>
</html>
#container {
  visibility: hidden;
}

#loader {
  color: #008cff;
  font-family: 'Helvetica Neue','calibiri';
  font-size: 14px;
  height: 40px;
  left: 45%;
  position: absolute;
  top: 45%;
  width: 30%;
}

You can also explore JavaScript File Upload feature tour page for its groundbreaking features. You can also explore our JavaScript File Upload example to understand how to browse the files which you want to upload to the server.

See Also