amazon-s3 - 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
解决方案
推荐阅读
- c# - 如何在 x 轴上平滑移动对象?
- java - 等待 executor 的线程由 executor submit 完成
- python - 是否允许在抽象类中使用用户定义的装饰器?或者,是否应该在继承后使用?
- salesforce - 你如何禁用 Apex:OutputField?
- python - Pandas:根据开始/结束分割点的字符串列表(重叠)将字符串列拆分为组件列
- ios - 如何在 Xcode 运行脚本中检测是否为 IBDesignable 构建 Storyboard
- vue.js - 如何在使用 v-for 时更新文本输入值
- javascript - 如何访问嵌套数组中的特定值
- firebase - 错误:Firebase:没有创建 Firebase 应用“[DEFAULT]”
- android - 关于在我的第一个 android 应用程序中使用 Selenium