fileBrowseHandler(files: any) {
if (files.target.files && files.target.files[0]) {
const reader: FileReader = new FileReader();
reader.readAsDataURL(files.target.files[0]);
reader.onload = () => {
this.preview = reader.result;
};
reader.onerror = (error) => {
console.log('Error: ', error);
};
}
}
Here is the explanation for the code above:
- files.target.files is an array-like object. It contains the files that the user has selected.
- FileReader object lets web applications asynchronously read the contents of files.
- reader.readAsDataURL(files.target.files[0]) is used to read the contents of the specified Blob or File.
- reader.onload is an event handler which is called when the read operation successfully completes.
- reader.onerror is an event handler which is called when the read operation fails.
- this.preview is a variable which stores the base64 image data of the selected file.
Top comments (0)