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.
get("FileUpload") . setValidators([ Validators. required, FileValidator. validate, fileSizeValidator(event), requiredFileType(["jpg", "png", "txt"]) ]);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With