まずは、ここからs3へのアクセスキーと、シークレットきーを取得してください。
S3 Bucketを作る
$ npm i --save aws-sdk
create-bucket.js
const AWS = require('aws-sdk');
// Enter copied or downloaded access ID and secret key here
const ID = '';
const SECRET = '';
// The name of the bucket that you have created
const BUCKET_NAME = 'test-bucket'; //同じバケット名は作れない ユニーク必須
const s3 = new AWS.S3({
accessKeyId: ID,
secretAccessKey: SECRET
});
const params = {
Bucket: BUCKET_NAME,
CreateBucketConfiguration: {
// アジアパシフィック (東京)
LocationConstraint: "ap-northeast-1"
}
};
s3.createBucket(params, function(err, data) {
if (err) console.log(err, err.stack);
else console.log('Bucket Created Successfully', data.Location);
});
こんな感じ。で、実行
$ node create-bucket.js
S3で画像をアップする
uplode-bucket.js
const fs = require('fs');
const AWS = require('aws-sdk');
// Enter copied or downloaded access ID and secret key here
const ID = '';
const SECRET = '';
const s3 = new AWS.S3({
accessKeyId: ID,
secretAccessKey: SECRET
});
const uploadFile = (fileName) => {
// Read content from the file
const fileContent = fs.readFileSync(fileName);
// Setting up S3 upload parameters
const params = {
Bucket: "test-bucket",
Key: 'uniquename.jpg', // 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('/Users/user-name/Desktop/test.png'); //ここにファイルの実体を入れる
こんな感じ。で、実行
$ node uplode-bucket.js
参考