How to ionic upload image and send image to api

nitish96
Nitish Sharma
Published on: October 17, 2024
Updated on: December 5, 2024
How to ionic upload image and send image to api blog

Ionic Upload image and take from camera and send data to API

1. Install camera Plugin


npm install @capacitor/camera
npx cap sync

2. create function for take photo and select image

selectedImage: string;
  async openCamera() {
    const image = await Camera.getPhoto({
      quality: 90,
      allowEditing: false,
      resultType: CameraResultType.Base64
  });
    this.selectedImage = `data:image/jpeg;base64,${image.base64String}`;
  }

3. Create Ionic UI for click this function and show Image

<ion-button type="button" (click)="openCamera()"><ion-icon slot="start" name="camera"></ion-icon> Take Photo </ion-button>
@if(selectedImage){
<ion-img [src]="selectedImage"  style="width:150px; height:150px;"></ion-img>

}
4.  Upload image to API
first image convert base64 to blob image

 base64ToBlob(base64Data: string, contentType: string): Blob {
    const byteCharacters = atob(base64Data);
    const byteNumbers = new Array(byteCharacters.length).fill(0).map((_, i) => byteCharacters.charCodeAt(i));
    const byteArray = new Uint8Array(byteNumbers);
    return new Blob([byteArray], { type: contentType });

  }
Now, create API function and convert image to formdata
uploadImage(){
let splitImage = this.selectedImage.split(',');
const imageBlob = this.base64ToBlob(splitImage[1], 'image/jpeg');
const imageName = `${Date.now()}.jpeg`;
const formData = new FormData();
formData.append('image', imageBlob, imageName);
this.http.post('/upload-image', formdata)
.subscribe((res)=>{
console.log("result", res);
})
}

// html
<ion-button type="button" (click)="uploadImage()">Upload Image</ion-button>

Comments

Login to leave a comment.

Build Software Application with Impact Hive