Search code examples
validationfile-uploadangular6mime-types

how to validate files before uploading in angular 6


How can I validate files before uploading in angular 4 and above?
i want file type and file size validation in angular 4 and above.
Screenshot of my issue

for each and every file I am getting correct file size and type except .msg file. How to get file type as application/vnd.ms-outlook application/octet-stream for outlook files. Please help me out.


Solution

  • Your question is a bit (lot) vague. I assume you mean, how do you get the File object from an input in Angular. Dead simple. The same way you would with vanilla(ish) JS.

    In your component, create a function to read your file:

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

    And apply it to the (change) event on your input in your template:

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

    You can do whatever you like with the file after that. The sample function just gets the size and type, as per your question.

    Stackblitz Example: https://stackblitz.com/edit/angular-vpvotz

    As a (slight) aside, rather than using any as the fileEvent type, you can define an interface to give you type hinting.

    interface HTMLInputEvent extends Event {
        target: HTMLInputElement & EventTarget;
    }
    

    While you're at it, also add the File type too. So your function becomes:

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

    But, you don't have to. Although any types are not recommended.