📅  最后修改于: 2023-12-03 15:34:47.626000             🧑  作者: Mango
在 ReactJS 中,我们可以通过以下步骤来获取 Amazon S3 服务中的私有图像对象:
aws-sdk
包来创建 Cognito 对象,代码如下:import AWS from 'aws-sdk';
const region = 'AWS_REGION';
const identityPoolId = 'IDENTITY_POOL_ID';
const cognito = new AWS.CognitoIdentity({
region: region
});
const params = {
IdentityPoolId: identityPoolId
}
cognito.getId(params, function(err, data) {
if (!err) {
console.log('Cognito Identity ID: ' + data.IdentityId);
}
});
const cognito = new AWS.CognitoIdentity({
region: region
});
const params = {
IdentityPoolId: identityPoolId
}
cognito.getCredentialsForIdentity(params, function(err, data) {
if (!err) {
console.log('AccessKeyId: ' + data.Credentials.AccessKeyId);
console.log('SecretAccessKey: ' + data.Credentials.SecretAccessKey);
console.log('SessionToken: ' + data.Credentials.SessionToken);
}
});
getObject
方法并将请求与临时的 AWS 认证证书一起发送。代码如下:const s3 = new AWS.S3({
apiVersion: '2006-03-01',
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
sessionToken: sessionToken
});
const getObjectParams = {
Bucket: 'BUCKET_NAME',
Key: 'OBJECT_KEY',
};
s3.getObject(getObjectParams, function(err, data) {
if (!err) {
console.log(data.Body.toString('ascii'));
}
});
这将返回一个包含图像数据的 JavaScript 对象。如果要在 ReactJS 中显示图像,可以将其转换为 Base64 编码并使用图像数据 URI。代码如下:
const base64Image = new Buffer(data.Body).toString('base64');
const imageSrc = 'data:image/jpeg;base64,' + base64Image;
return (
<div>
<img src={imageSrc} />
</div>
);
现在,我们就可以在 ReactJS 应用程序中获取 S3 中的私有图像对象了!