nativescript图片上传到s3编码问题

时间:2019-04-17 16:29:52

标签: amazon-s3 nativescript angular2-nativescript

我在将图像从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);
    });
  }

当我打开文件时,这就是我看到的 enter image description here

,并且S3对象上的元数据看起来正确 enter image description here 当我下载文件并在NP ++中打开它时,我看到了base64值。

iVBORw0KGgoAAAANSUhEUgAAB4AAAASwCAIAAACVUsChAAAAA3NCSVQI...

我也无法打开下载的图像 enter image description here


ATTEMPT 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

0 个答案:

没有答案