不使用 Node Js 中的访问密钥和秘密密钥将文件上传到 S3 Bucket

时间:2021-06-04 05:11:41

标签: node.js amazon-web-services amazon-s3

虽然我可以使用访问密钥和密钥将文件上传到 s3 存储桶。 和 我正在尝试在不使用访问密钥和密钥的情况下将文件上传到 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);

2 个答案:

答案 0 :(得分:0)

在 SDK for JavaScript 中使用来自实例角色的凭据的说明如下:

<块引用>

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

答案 1 :(得分:0)

这是我们可以在不使用任何访问密钥或秘密密钥的情况下将文件上传到 s3 存储桶的一种方式。您可以在 AWS 中创建 congnito 池 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];
    }