首页 > 解决方案 > 在 Node Js 中不使用访问密钥和密钥将文件上传到 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);

标签: node.jsamazon-web-servicesamazon-s3

解决方案


在 SDK for JavaScript 中使用来自实例角色的凭据在以下内容中进行了说明:

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


推荐阅读