nick zdravcov nick zdravcov - 3 months ago 22
TypeScript Question

Can't upload file and convert it to base64string

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);
}

Answer

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);

    }
Comments