Angular 7 上传base64形式的图片到s3

Angular 7 upload image to s3 which is in base64 form

在 Ionic 4 angular 7 中,应用程序试图从 Cordova 相机插件上传图像。

Camera 插件的输出是 base64 图像数据。

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

我正在生成预签名的 AWS S3 URL 以在服务器端上传图像。

例如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

下面的代码没有给出任何错误,但是上传的图像只是黑屏而不是实际图像。

HTTP PUT 图像到 S3 的正确方法是什么,可用的图像采用 base64 编码格式?

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

使用 Postman 上传通过选择二进制数据工作。
所以我继续使用 ionic 4 和 httpclient 复制相同的内容


Convert a binary NodeJS Buffer to JavaScript ArrayBuffer
https://github.com/aws/aws-sdk-js/issues/2141

步骤:
1. 安装:npm install buffer
2. 更新 tsconfig.app.json 包含类型": ["node"] in "compilerOptions"
3. 添加 (window as any).global = window;在 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();
}