AWS S3 node.js SDK上传了文件和文件夹权限

时间:2013-01-17 09:31:09

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

我正在使用aws-sdk包将文件上传到S3:

fs.readFile(sourceFile, function (err, data) {
    if (err) { throw err; }

    s3.client.putObject({
        Bucket: bucketName,
        Key: 'Folder/image.jpg',
        Body: data
    }, function (res) {
            console.log('Successfully uploaded file.');
        })

});

我需要将上传的文件通过cloudfront下载,如果我认为正确,我需要设置文件权限:每个人打开/下载,Folder2应该公开(通过菜单Make Public)。所以有2个问题:

1)如何在上传的文件\文件夹中设置\ modify权限?

2)如何使用AWS SDK for node.js公开文件夹。

3 个答案:

答案 0 :(得分:77)

找到它 http://docs.aws.amazon.com/AmazonS3/latest/dev/ACLOverview.html#CannedACL

需要在putObject中添加选项:

ACL:'public-read'

答案 1 :(得分:5)

这是一个工作代码段,该代码段将本地文件(test-file.gif)上传到S3存储桶,并打印出一个URL供所有人下载。

const fs = require('fs');
const AWS = require('aws-sdk');
AWS.config.update({ region: 'us-west-1' });

// Fill in your bucket name and local file name:
const BUCKET_NAME = 'test-bucket-name-goes-here'
const FILE_NAME_LOCAL = './test-file.gif'
const FILE_NAME_S3 = 'this-will-be-the-file-name-on-s3.gif'
const FILE_PERMISSION = 'public-read'

// Create S3 service object
s3 = new AWS.S3({ apiVersion: '2006-03-01' });

// Get file stream
const fileStream = fs.createReadStream(FILE_NAME_LOCAL);

// Call S3 to retrieve upload file to specified bucket
const uploadParams = {
    Bucket: BUCKET_NAME,
    Key: FILE_NAME_S3,
    Body: fileStream,
    ACL: FILE_PERMISSION
};

s3.upload(uploadParams, function (err, data) {
    if (err) {
        console.log("Error", err);
    } if (data) {
        console.log("Upload Success", data.Location);
    }
});

答案 2 :(得分:0)

以下内容具有魅力。 (请注意参数中的ACL键

const params = {
  Bucket: bucketName + path,
  Key: key,
  Body: buffer,
  ContentEncoding: 'base64',
  ContentType: 'image/jpeg',
  ACL:'public-read'
};
await s3.putObject(params).promise();

注意:IAM权限“ s3:PutObjectACL ”必须包含在适当的策略中,否则会出现访问被拒绝错误。