首页 > 解决方案 > nativescript 图像上传到 s3 编码问题

问题描述

我在将图像从 Nativescript 上传到 AWS 时遇到问题,我很确定这是配置问题。

选择一张图片

    const context = imagepicker.create({
      mode: 'single' // use "multiple" for multiple selection
    });
    await context.authorize();
    const selection: Array<ImageAsset> = await context.present();
    const imageAsset = selection[0];
    const source: ImageSource = await new ImageSource().fromAsset(imageAsset);
    const fileLocation = imageAsset.android ? imageAsset.android : imageAsset.ios;
    const fileType = mime.extension(mime.lookup(fileLocation));
    const image = source.toBase64String(fileType);
    console.log(image);

此时的图像是:iVBORw0KGgoAAAANSUhEUgAAB4AAAASwCAIAAACVUsChAAAAA3NCSVQI...

此时的图像位置是:/storage/emulated/0/DCIM/Screenshots/Screenshot_20181106-150854.png

const fileLocation = imageAsset.android ? imageAsset.android : imageAsset.ios;
const signedUrl = await this.getSignedUrl(fileLocation);

获取签名URL的后端代码

const getSignedUrlPromise = (operation, params) => {
  return new Promise((resolve, reject) => {
    s3.getSignedUrl(operation, params, (err, url) => {
      err ? reject(err) : resolve(url);
    });
  });
}
  const params = { 
    Bucket: BUCKET_NAME, 
    Key: `abc123/456/3/${fileName}`,
    ContentType: contentType,
    ContentEncoding: 'base64'
  }
  const url = await getSignedUrlPromise('putObject', params).catch(err => {
    console.log('error', JSON.stringify(err))
    return {
      statusCode: 400,
      body: JSON.stringify(err)
    }
  });
  console.log('success', url);
  return {
    statusCode: 200,
    body: JSON.stringify({ url: url })
  }

此时的signedUrl是:

https://myproject.s3.amazonaws.com/abc123/456/3/Screenshot_20181106-150854.png?AWSAccessKeyId=xxxxxxxxxxxxxx&Content-Encoding=base64&Content-Type=image%2Fpng&Expires=1555517358&Signature=yyyyyyyy&x-amz-security-token=long_token

然后,使用signedURL,我上传图片:

    const mimeType = mime.lookup(fileLocation);
    this.http.put(signedUrl, image, {
      headers: {
        'Content-Type': mimeType,
        'Content-Encoding': 'base64'
      }
    }).subscribe((resp) => {
      console.log('resp2', resp);
    });
  }

当我打开文件时,这就是我看到的 在此处输入图像描述

并且 S3 对象上的元数据看起来正确 在此处输入图像描述 当我下载文件并在 NP++ 中打开它时,我看到了 base64 值。

iVBORw0KGgoAAAANSUhEUgAAB4AAAASwCAIAAACVUsChAAAAA3NCSVQI...

我也无法打开下载的图像 在此处输入图像描述


尝试 2

我看到有些人在哪里使用缓冲区,所以我将image代码更改为

const image = Buffer.from(source.toBase64String(fileType).replace(/^data:image\/\w+;base64,/, ''), 'base64');

图像仍然损坏,当我使用 NP++ 下载并打开文件时,我看到了

{"type":"Buffer","data":[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,7,128,0,0,4,176,8,2,0,0,0

标签: amazon-s3nativescriptangular2-nativescript

解决方案


推荐阅读