따라해보면 쉽습니다.
AWS EC2 서버에서 공지사항에 들어가는 첨부 파일을 업로드 하고 다운로드 하는 기능이 필요 했다.
다음의 순서로 처리하면 쉽게 된다.
이후 결과로 Access key ID, Secret access key를 알고 있어야 한다.
# 프로젝트 초기화
$> npm init # aws-sdk 모듈 설치
$> npm install aws-sdk --save
createBucket.js
const AWS = require('aws-sdk');
const ID = 'Access key Id';
const SECRET = '';
const BUCKET_NAME = '';
const s3 = new AWS.S3({ accessKeyId: ID, secretAccessKey: SECRET });
const params = {
Bucket: BUCKET_NAME,
CreateBucketConfiguration: {
// Set your region here
LocationConstraint: "ap-northeast-2"
}
};
s3.createBucket(params, function(err, data) {
if (err) console.log(err, err.stack);
else console.log('Bucket Created Successfully', data.Location);
});
uploadFile.js
const fs = require('fs');
const AWS = require('aws-sdk');
const BUCKET_NAME = '';
const s3 = new AWS.S3({ accessKeyId: '', secretAccessKey: '' });
const uploadFile = (fileName) => {
const fileContent = fs.readFileSync(fileName);
const params = {
Bucket: BUCKET_NAME,
Key: 'test.txt', // File name you want to save as in S3
Body: fileContent }
;
s3.upload(params, function(err, data) {
if (err) { throw err; }
console.log(`File uploaded successfully. ${data.Location}`);
});
};
uploadFile('./uploads/test.txt');
download.js
const fs = require('fs');
const AWS = require('aws-sdk');
const BUCKET_NAME = '';
const s3 = new AWS.S3({ accessKeyId: '', secretAccessKey: '' });
const downloadFile = (fileName) => {
const params = {
Bucket: BUCKET_NAME,
Key: 'test.txt', // File name you want to save as in S3
};
s3.getObject(params, function(err, data) {
if (err) {
throw err;
}
fs.writeFileSync(fileName, data.Body.toString());
});
};
downloadFile('../../uploads/test-download.txt');