LoginSignup
5
4

More than 3 years have passed since last update.

『コピペOK』NodeでS3へ画像アップロード【2020】

Last updated at Posted at 2020-04-07

まずは、ここから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

参考

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4