7

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.

1
  • 1
    This is not the way to ask a question. Please read: stackoverflow.com/help/how-to-ask You have given no context as to what you are doing. What you have done. Commented Aug 12, 2018 at 21:15

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

How to check .msg files(outlook) file type? while checking, I am getting empty string.
Assuming you have your file read in correctly, you should be checking file.type for a type of application/vnd.ms-outlook.... failing that, check the extension on the filename... e.g isEmail(file: File) { return file.name.substring(file.name.length - 4, file.name.length) === '.msg';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.