AWS S3 node.js SDK uploaded file and folder permissions

后端 未结 3 1250
有刺的猬
有刺的猬 2021-01-31 13:48

I\'m uploading file to S3 using aws-sdk package:

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

    s3.client.putObject({
        Bu         


        
相关标签:
3条回答
  • 2021-01-31 14:20

    Found it http://docs.aws.amazon.com/AmazonS3/latest/dev/ACLOverview.html#CannedACL

    need to add option in putObject or upload:

    ACL:'public-read'
    
    0 讨论(0)
  • 2021-01-31 14:20

    The following works like a charm. (Note the ACL key in params)

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

    Note: IAM permission "s3:PutObjectACL" must be included in the appropriate policy otherwise you will get Access Denied errors.

    0 讨论(0)
  • 2021-01-31 14:24

    Here is a working code snippet that uploads a local file (test-file.gif) to S3 bucket and prints out a URL for everyone to download.

    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);
        }
    });
    
    0 讨论(0)
提交回复
热议问题