Ionic 4 multiple images base64 conversion for upload

There are various ways to save image data on server side. One of the way is to convert images data to base64 and store it in databases like MongoDb. In this post we are going to see how we can use ioninput to select multiple images and then convert those to base64 format.

To select images we need to specify type attribute of ion-input as file and accept attribute as image/*;capture=camera this will make ion-input to allow selection of only image files or open camera to capture image. Below is code snippet for all this. You can also restrict image file types using accept attribute.

<ion-item>              <ion-label position="stacked">Images</ion-label>                <ion-input (change)="convertToBs64($event)" multiple="true" type="file" accept="image/*;capture=camera"></ion-input>            </ion-item>

Next is we need to call a method on change event of ion-input. Remember not to use ionChange event as it does not return all the information of selected files i.e., FileList object. Lets name this method as convertToBs64(). In this method we will be passing element event as parameter so that we can files data from event.target. Then we need to user FileReader which provide a method readAsDataURL() which help us to convert file data to base64 string. Below is complete code snippet of convertToBs64() function.

convertToBs64(event) {        this.imgs = [];        Array.prototype.forEach.call(event.target.files, (fileItem) => {            const reader = new FileReader();            let baseString;            reader.onload = () => {                baseString = reader.result;                if (baseString) {                    if (!this.imgs) {                        this.imgs = [];                    }                    this.imgs.push(baseString);                }            };            reader.readAsDataURL(fileItem);        });    }

To view base64 converted images simple iterate over list variable using *ngFor. Below is code snippet for that. 

<ion-grid no-padding="">                <ion-row>                    <ion-col size="3" *ngFor="let img of list?.imgs">                        <ion-img [src]="img"></ion-img>                    </ion-col>                </ion-row>            </ion-grid>

Below are some of the screenshot of how the views will appear

    

Note : ion-input with multiple attribute doesn’t work in android app. Its know bug.  

Comments

Popular posts from this blog

MATLAB code for Circular Convolution using Matrix method

Positive number pipe in angular 2+