Ionic 6 Capacitor Camera - upload to server

-1

I am building a user profile app with ionic capacitor in Angular and require the user to upload an image directly from camera to the live server through our API.

I found a lot of documentation that first saves the image to fileSystem in temp directory, but nothing that just uploads and sends to server.

I have this function to select image

async selectImage() {
    const image = await Camera.getPhoto({
        quality: 90,
        allowEditing: false,
        resultType: CameraResultType.Uri,
        source: CameraSource.Prompt // Camera, Photos or Prompt!
    });
  }

and this function to upload image from fileSystem to API

async startUpload(file: LocalFile) {
    const response = await fetch(file.data);
    const blob = await response.blob();
    const formData = new FormData();
    formData.append('file', blob, file.name);
    this.uploadData(formData);
  }

    // Upload the formData to our API
  async uploadData(formData: FormData) {
    const loading = await this.loadingCtrl.create({
        message: 'Uploading image...',
    });
    await loading.present();

    // Use your own API!
    const url = 'http://localhost:8888/images/upload.php';

    this.http.post(url, formData)
        .pipe(
            finalize(() => {
                loading.dismiss();
            })
        )
        .subscribe(res => {
            if (res['success']) {
                this.presentToast('File upload complete.')
            } else {
                this.presentToast('File upload failed.')
            }
        });
  }

Using the fileSystem I can effectively upload the image to the server, this is no problem, I would like to skip the filesystem and go direct but cannot seem to figure this out.

Any help?

Have you tried to do not use the Capacitor Camera Plugin? There is other ways, like use <input type='file' accept='image/*'>. You can convert the Blob response into base64 and send to your server. It works for you?

Best regards!

1 Like