Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 868
Aashish Chakravarty Avatar asked Aug 12 '18 19:08

Aashish Chakravarty


People also ask

How do you validate the input type file size in reactive form?

get("FileUpload") . setValidators([ Validators. required, FileValidator. validate, fileSizeValidator(event), requiredFileType(["jpg", "png", "txt"]) ]);

How to restrict file upload size in Angular?

You can restrict the maximum allowed file size (in bytes) by using the maxFileSize property. If the selected file exceeds the maximum size, an error message will be displayed.


1 Answers

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.

like image 144
prettyfly Avatar answered Oct 06 '22 17:10

prettyfly