Converting Image to base64 string in Typescript
This is something i have done to upload a profile picture i have also checked for size less than 512KB and then i have posted that image to my API in next function
i have used FileReader() and readAsDataURL() to convert the file to base64
/* On Change Profile image*/
onProfileChange(event:any) {
if(event.target.files && event.target.files[0]) {
if(event.target.files[0].type && event.target.files[0].type.split('/')[0] == ["image"] && event.target.files[0].size <= 512000){
this.file = event.target.files[0];
var reader = new FileReader();
reader.onload = (event:any) => {
this.Image = event.target.result;
}
reader.readAsDataURL(event.target.files[0]);
this.isBrowser = false;
} else {
this.isBrowser = true;
this._toastr.error("Max image upload size is 500KB only");
}
}
}
/*end Of On Change profile Image*/
/*Image api*/
AddImage(event: any){
let data=new FormData();
if(this.file){
data.append('image',this.file);
this._db.Post('api/users/image',data).subscribe(b=>{
if(b.IsResult){
this._toastr.success(b.ResultMsg);
this.getProfileDetail();
this.isBrowser=true;
}
});
}else{
this._toastr.error("Something went wrong");
}
}
You need to use readAsDataUrl()
:
function getBase64(event) {
let me = this;
let file = event.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
//me.modelvalue = reader.result;
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}