NodeJS 配置AWS S3存储桶策略

nqwrtyyt  于 2023-02-08  发布在  Node.js
关注(0)|答案(2)|浏览(171)

如何配置AWS S3 bucket策略,使上传的文件可以作为公共文件读取。有人能给予节点js代码一个例子吗?
我是这个领域的新手,所以我没有这方面的经验。任何帮助都非常感谢。

yquaqz18

yquaqz181#

此过程有几个步骤,本说明适用于nodejs 14(运行时:nodejs14.x)登录AWS帐户后,首先您必须遵循以下链接格式您应该遵循以下格式。https://s3.console.aws.amazon.com/s3/buckets/{BUCKET-NAME}?region = {REGION} & tab = permissions #
这是一个示例链接
https://s3.console.aws.amazon.com/s3/buckets/logo?region=us-east-1&tab=permissions#
图像:This is an example of entering the path
第二步是创建bucket策略。将单词"BUCKET-NAME"替换为bucket的名称。

{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "AllowPublicRead",
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:PutObject",
        "Resource": "arn:aws:s3:::BUCKET-NAME/*",
        "Condition": {
            "StringEquals": {
                "s3:x-amz-acl": "public-read"
            }
        }
    }
]

}
图像:Bucket policies JSON configuration
然后按照以下代码在serverless. yml上创建一个端点。file_upload函数包含在handler. js文件中。

    • 无服务器. yml**
file_upload:
    handler: handler.file_upload
    timeout: 15
    events:
      - httpApi:
          path: /file-upload
          method: post

之后,您必须按如下所示编写handler. js文件

    • 处理程序. js**
'use strict';
const AWS = require("aws-sdk");
const s3 = new AWS.S3()
const { Validator } = require('node-input-validator');

const MAX_SIZE = 2097152 // 2MB
const bucket = 'S3_BUCKET-NAME' // Name of your bucket.
const Busboy = require("busboy")

s3.config.update({
  region: "us-east-1",
  accessKeyId: 'S3_ACCESS_KEY_ID',
  secretAccessKey: 'S3_SECRET_ACCESS_KEY'
});

const sendJSON = (code, message, data) => {
    let resData = {
        "status": code < 400 ? 'Success' : 'Error',
        "message": message,
    }
    data ? (resData["data"] = data) : null;
    return {
        statusCode: code,
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            ...resData
        })
    };
}

const FORM = {
    parse(body, headers) {
        return new Promise((resolve, reject) => {
            const data = {};
            const buffer = Buffer.from(body, 'base64');
            const bb = Busboy({
                headers: Object.keys(headers).reduce((newHeaders, key) => {
                    // busboy expects lower-case headers.
                    newHeaders[key.toLowerCase()] = headers[key];
                    return newHeaders;
                }, {}),
                limits: {
                    fileSize: MAX_SIZE, // Set as desired.
                    files: 1,
                },
            });

            bb.on('file', (name, stream, info) => {
                const chunks = [];

                stream.on('data', (chunk) => {
                    if (name === 'File') {
                        chunks.push(chunk);
                    } else {
                        reject(new Error('File not found.'));
                    }
                }).on('limit', () => {
                    reject(new Error('File size limit has been reached.'));
                }).on('close', () => {
                    if (name === 'File') {
                        data[name] = Buffer.concat(chunks);
                        data['ContentType'] = info.mimeType;
                        data['FileName'] = info.filename;
                    }
                });
            });
            bb.on('field', (name, val, info) => {
                data[name] = val;
            });
            bb.on('error', (err) => {
                reject(err);
            });
            bb.on('close', () => {
                resolve(data);
            });

            bb.end(buffer);
        });
    }
};
const uploadToS3 = (bucket, key, buffer, mimeType) =>
    new Promise((resolve, reject) => {
        s3.upload(
            { Bucket: bucket, Key: key, Body: buffer, ContentType: mimeType, ACL: 'public-read' },
            function (err, data) {
                if (err) reject(err);
                resolve(data)
            })
    });

module.exports.file_upload = async (event) => {
  try {
        const data = await FORM.parse(event['body'], event['headers']);
        const validations = new Validator(data, {
            File: 'required'
        });
        const.path = data.path? data.path : null;
        const matched = await validations.check();
        if (!matched) {
            return sendJSON(400, validations.errors);
        }
        const date = Math.floor(Date.now() / 1000);
        const list = data.FileName.split(".");
        const originalKey = `${PATH}/${Date.now()}_${md5(list[0])}.${list[list.length-1]}`; // "PATH" is your sub-folder path in S3.
        const originalFile = await Promise.all([
            uploadToS3(bucket, originalKey, data.File, data.ContentType)
        ]);
        const file_name = originalFile[0]['Key'];
        return sendJSON(201, 'Successfully saved.', originalFile);
  } catch (e) {
    return sendJSON(400, e.message);
  }
};

下面附有AWS文档的链接
https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-bucket-policies.html

sc4hvdpw

sc4hvdpw2#

您可以查看此official documentation of AWS s3 for NodeJS,它解释了如何更新存储桶策略

相关问题