unsafePtr
unsafePtr

Reputation: 1773

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

Upvotes: 3

Views: 531

Answers (2)

Luke P. Issac
Luke P. Issac

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

Marco Castano
Marco Castano

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

Related Questions