1

In Ionic 4 angular 7 application trying to upload an image from the Cordova camera plugin.

The output from the Camera plugin is base64 image data.

this.camera.getPicture(options).then((imageData) => {
  // imageData is either a base64 encoded string or a file URI
  // If it's base64 (DATA_URL):
  const base64Image = 'data:image/jpeg;base64,' + imageData;

  this.uploadImage(url, base64Image )
}, (err) => {
  // Handle error
}); 

I am generating an AWS S3 pre-signed URL to upload an Image on server side.

e.g http://127.0.0.1/gdcom/63a5d901-7966-11ea-bf01-a7a6315cc36d/d418baf3-8129-11ea-a67d-3646e8bf199f.jpeg?AWSAccessKeyId=remote-identity&Expires=1587183624&Signature=mC6CRT6sPVKeCKM0aVj%2ByKzDy%2F8%3D

Below code does not give any error, but the uploaded image is just a black screen and not the actual image.

What is the correct way to HTTP PUT an Image to S3, the available image in base64 encoded format?

uploadImage(url: string, imageData: any): Promise<any> {
    const headers = new HttpHeaders({'Content-Type': 'image/jpeg;'});

    return this.http.put(url, imageData, {headers: headers})
        .pipe(
            tap(data => console.log(JSON.stringify(data))),
            catchError(this.handleError('uploadImage'))
        ).toPromise();
}
Pravin
  • 730
  • 1
  • 7
  • 16

1 Answers1

2

Uploading using Postman was working by selecting binary data.
So I went ahead and replicated same with ionic 4 and httpclient be referring

Angular 5 HttpClient post raw binary data
Convert a binary NodeJS Buffer to JavaScript ArrayBuffer
https://github.com/aws/aws-sdk-js/issues/2141

Steps :
1. Install : npm install buffer
2. Update tsconfig.app.json include types": ["node"] in "compilerOptions"
3. Add (window as any).global = window; in src/app/pollyfills.ts

uploadImage(url: string, contentType: string, imageData: any): Promise<any> {
    const headers = new HttpHeaders();
    if (contentType === 'jpeg') {
        headers.set('Content-Type', 'image/jpeg;');
    } else if (contentType === 'png') {
        headers.set('Content-Type', 'image/jpeg;');
    }

    const data = imageData.replace(/^data:image\/\w+;base64,/, '');
    const buff = new Buffer(data, 'base64');

    return this.http.put(url, buff.buffer, {headers: headers})
        .pipe(
            tap(data => console.log(JSON.stringify(data))),
            catchError(this.handleError('uploadImage'))
        ).toPromise();
}
Pravin
  • 730
  • 1
  • 7
  • 16