将文件上传到S3 Bucket,无需使用Node Js中的访问密钥和密钥



虽然我可以使用访问密钥和密钥将文件上传到s3 bucket。以及我试图在不使用访问密钥和密钥的情况下将文件上传到AWS s3 bucket。请帮帮我。这是我的代码,

import {path} from "path";
const fs = require('fs');
const AWS = require('aws-sdk');
AWS.config.update({region: 'Region'});
// Enter copied or downloaded access ID and secret key here
const ID = 'id';
const SECRET = 'id';
// The name of the bucket that you have created
const BUCKET_NAME = 'name';
const s3 = new AWS.S3({
accessKeyId: ID,
secretAccessKey: SECRET
});
const FILE_PATH = 'filepath';

const uploadFile = (fileName) => {
// Read content from the file
const fileContent = fs.readFileSync(fileName);
// Setting up S3 upload parameters
const params = {
Bucket: BUCKET_NAME,
Key: path.basename(FILE_PATH), // File name you want to save as in S3
Body: fileContent
};
// Uploading files to the bucket
s3.upload(params, function(err, data) {
if (err) {
throw err;
}
console.log('File uploaded successfully. ${data.Location}');
});
};
uploadFile(FILE_PATH);

JavaScript SDK中实例角色的信任细节的使用说明如下:

  • 从Amazon EC2的IAM角色在Node.js中加载凭据

SDK自动为您的应用程序选择IAM凭据,无需手动提供凭据。

这是我们可以在不使用任何访问密钥或密钥的情况下将文件上传到s3 bucket的一种方法。您可以在AWS中创建congnito池id。

所以我的问题是如何在不使用访问密钥和密钥的情况下将文件上传到s3 bucket。。。

下面我已经写了我的问题的解决方案

private async uploadFile(fileName: string) {
CustomLogger.logger.info('Inside File Upload Method');

AWS.config.region = 'ADD YOUR REGION';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'ADD YOUR COGNITO ID'
});
const BUCKET_NAME = 'ADD YOUR BUCKET NAME';
const s3 = new AWS.S3({
region: AWS.config.region,
credentials: AWS.config.credentials
});
const fileContent = fs.readFileSync(fileName);
const params = {
Bucket: BUCKET_NAME,
Key: LpServiceImpl.getZipFileName(fileName),
Body: fileContent
};
s3.upload(params, (err: Error, data: any) => {
if (err) {
CustomLogger.logger.info('File upload failed.');
throw err;
}

CustomLogger.logger.info('File uploaded successfully.' + data.Location);
});
};
private static getZipFileName(filePath: string){
const n = filePath.split("\");
CustomLogger.logger.info('Split Successfully');
return n[n.length - 1];
}

最新更新