15
11

More than 5 years have passed since last update.

【Node.js】postで受け取った画像をS3へアップロードする

Last updated at Posted at 2018-12-17

はじめに

おはこんばんにちは@kaoryuuuです。
今回はnodeで実装したAPIでPOSTされた画像をS3へアップロードする方法を紹介していこうと思います。

今回やること

base64エンコードされた画像を受け取り、画像をS3へアップロードする

install

npm install dotenv
npm install aws-sdk

envファイル

ルートディレクトリに.envを作成し、リージョン情報などを作成してください。
※アクセスキーなどはaws-cli上で設定しています。
こちらを参考にしてます。
https://docs.aws.amazon.com/ja_jp/cli/latest/userguide/cli-chap-getting-started.html

AWS_REGION = ""
AWS_BUCKET_NAME = ""

アップロード処理

S3へのファイル名となるパスはユニークになるようにディレクトリを切って対応しています。
こうすることで機能ごとに参照することができるようになります。
※今回は 機能/ユーザーID/ファイル名の構成にしています。

posts.js
import S3 from '../../s3';
import crypto from 'crypto';

router.post('/', (req, res) => {

    const timeStamp = Date.now();
    const encodedData = req.body.thumbnail;
    const fileData = encodedData.replace(/^data:\w+\/\w+;base64,/, '')
    const decodedFile = new Buffer(fileData, 'base64')
    // ファイルの拡張子(png)
    const fileExtension = encodedData.toString().slice(encodedData.indexOf('/') + 1, encodedData.indexOf(';'))
    // ContentType(image/png)
    const contentType = encodedData.toString().slice(encodedData.indexOf(':') + 1, encodedData.indexOf(';'))
    const hashName = crypto.createHash('md5').update(`${timeStamp}${fileData}`).digest('hex');
    const fileName = [hashName, fileExtension].join('.');
    const uploadType = "foo";
    const s3 = new S3();

    s3.uploadImage(id, decodedFile, contentType, fileName, uploadType)
        .then(() => {
           // 何か処理
        }
    })
});
S3.js
import dotenv from 'dotenv';
import aws from 'aws-sdk';

dotenv.config();
aws.config.update({
    region: process.env.AWS_REGION
});

export default class S3 {

    uploadImage(userId, decodedFile, contentType, fileName, uploadType) {

        const params = {
            Body: decodedFile,
            Bucket: process.env.AWS_BUCKET_NAME,
            Key: `${uploadType}/${userId}/${fileName}`,
            ContentType: contentType
        }
        const s3 = new aws.S3()
        return s3.putObject(params).promise()
                    .catch((err) => { console.log(`Error: ${err}`) }) 
    }
}
15
11
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
15
11