在Node.js中上传文件到S3存储桶而不使用访问密钥和秘密密钥

3
尽管我可以使用访问密钥和秘密密钥将文件上传到S3存储桶。 AND 我正在尝试上传一个文件到AWS S3存储桶,但不使用访问密钥和秘密密钥。请协助我。 这是我的代码:
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);

1
如果不是来自您的访问密钥和秘密密钥,那么AWS凭据将从哪里获取? - Marcin
1
需要更多细节。您的应用程序托管在哪里?Lambda?EC2?本地? - Ninad Gaikwad
我使用了一个 EC2。 - Lahiru Ferreira
@LahiruFerreira AWS SDK 会自动检查实例角色,因此您不必在代码中显式地执行此操作。 - Marcin
@marcin,你能否提供一些从头开始的文档链接或博客链接?那将非常有帮助! - Lahiru Ferreira
显示剩余6条评论
2个回答

1

我已经使用那个一段时间了,但我想知道是否可以从开发环境中做类似的事情? - Wayne Smallman
1
@WayneSmallman 为什么不为此创建一个专门的问题? - Marcin

0
这是一种我们可以上传文件到S3存储桶的方法,而不需要使用任何访问密钥或秘密密钥。您可以在AWS中创建一个Cognito池ID。
所以我的问题是如何在不使用访问密钥和秘密密钥的情况下上传文件到S3存储桶...
以下是我为自己的问题编写的解决方案。
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];
    }

请不要仅仅发布代码作为答案,还要提供解释您的代码是如何解决问题的。带有解释的答案通常更有帮助和更高质量,并且更有可能吸引赞同。 - Tyler2P
@Tyler2P 我已经编辑了答案并添加了一些解释。 - Lahiru Ferreira

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接