Reputation: 1773
I'm trying to upload file, then convert it to base64 string and add to object. but it seems did'nt work. console.log() every time show empty object
<input type="file" (change)="onChange($event)" accept="image/jpeg, image/png" />
<input type="submit" value="send" (click)="upload()" />
functions:
onChange(fileInput: any) {
let image: any = fileInput.target.files[0];
let reader: FileReader = new FileReader();
reader.onload = () => {
reader.readAsDataURL(image);
let photo: AddPhoto = new AddPhoto();
photo.base64Image = reader.result;
this.product.photos = [];
this.product.photos.push(photo);
};
}
upload() {
console.log(this.product);
}
Upvotes: 3
Views: 531
Reputation: 1591
One thing here is that, reader.onload will be called only when the file is successfully loaded by reader.readAsDataURL(). Here logically it should not be written inside reader.onload. Take readAsDataURL outside the onload function so that it remains inside onChange function. Then it should work. You code should look something as follows.
onChange(fileInput: any) {
let image: any = fileInput.target.files[0];
let reader: FileReader = new FileReader();
reader.onload = () => {
let photo: AddPhoto = new AddPhoto();
photo.base64Image = reader.result;
this.product.photos = [];
this.product.photos.push(photo);
};
reader.readAsDataURL(image);
}
Upvotes: 1
Reputation: 1154
This works well for me...hope it helps
uploadFileImage(fileInput: any)
{
var files = fileInput.target.files;
var file = files[0];
if (files && file)
{
var reader = new FileReader();
reader.onload = function(readerEvt: any)
{
var binaryString = readerEvt.target.result;
var base64 = btoa(binaryString);
this.product.photos = [];
this.product.photos.push(base64);
};
reader.readAsBinaryString(file);
}
}
Upvotes: 1