In this article we will be discussing about validating a file/image from client side before uploading. In my previous articles I have covered file upload and showing a preview image while uploading, now let us check the validation part.
Component
import { Component } from '@angular/core';
import { commonService } from './services/commonService'
@Component({
selector: 'app-root',
template: '<div>'
+ '<input type="file" (change)="upload($event)">'
+ '</div>',
})
export class AppComponent {
constructor(private _service: commonService) { }
upload(event: any) {
let files = event.target.files;
//check file is valid
if (!this.validateFile(files[0].name)) {
console.log('Selected file format is not supported');
return false;
}
let fData: FormData = new FormData;
for (var i = 0; i < files.length; i++) {
fData.append("file", files[i]);
}
var _data = {
filename: 'Sample File',
id: '0001'
}
fData.append("data", JSON.stringify(_data));
this._service.uploadFile(fData).subscribe(
response => console.log(response),
error => console.log(error)
)
}
}
Validation
validateFile(name: String) {
var ext = name.substring(name.lastIndexOf('.') + 1);
if (ext.toLowerCase() == 'png') {
return true;
}
else {
return false;
}
}
Here we are taking the file/image extension and validating before uploading to backend. Similar way you can check other extensions as well.
if (ext.toLowerCase() == 'war')
if (ext.toLowerCase() == 'csv')
if (ext.toLowerCase() == 'jpeg')
...etc
We are done. In this article we have discussed about validating a file/image before uploading to backend.
Related Info
1. File/Image upload validation- Angular
2. File/Image upload and send data to backend
3. Show preview image while uploading file/image
4. Rating star component - Angular
5. Date filtering and formatting - Angular
how to store file to local directory?
ReplyDeleteAny way to also validate for malicious file?
ReplyDelete