How can I convert an image to base64 in Angular 2? The image is uploaded from the local filesystem. Currently, I am using fileLoadedEvent.target.result to achieve this. However, when I try to send this base64 string through REST services to Java, it fails to decode. Even when I use free online encoder-decoder tools, I am unable to see the decoded image. I have also attempted using canvas but without success. It seems that the base64 string generated is not proper. Do I need to add any specific package for this task in Angular 2? Or is there a particular method to encode images to base64 as seen in Angular 1 with the angular-base64-upload package?
Below is a snippet of my code:
onFileChangeEncodeImageFileAsURL(event:any,imgLogoUpload:any,imageForLogo:any,imageDiv:any)
{
var filesSelected = imgLogoUpload.files;
var self = this;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
//Reading Image file, encode and display
var reader: FileReader = new FileReader();
reader.onloadend = function(fileLoadedEvent:any) {
//SECOND METHO
var imgSrcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = imageForLogo;
newImage.src = imgSrcData;
imageDiv.innerHTML = newImage.outerHTML;
}
reader.readAsDataURL(fileToLoad);
}
}