LoginSignup
9
10

More than 5 years have passed since last update.

AWS LambdaからS3にbase64encodeの画像ファイルを保存

Last updated at Posted at 2016-06-09

何回もこのソース書いてる気がするから、自分のメモ用に。
書いたタイミングではjpegだけしか必要なかったため、jpegチェックをいれてある。
外部依存モジュールなしで、Lambda codeで動作。
Node.js 4.3をRuntimeに。

エラー処理ちょっと直しました。

node.js
var aws = require('aws-sdk');

var s3 = new aws.S3({ apiVersion: '2006-03-01', region: '{aws-region}' });
var BUCKET_NAME = '{BUCKET_NAME}';
var DIRECTORY_PATH = '{SAVE_DIRECTORY}'

exports.handler = function(event, context) {

    var fileName = '/' + event.name + '.jpg';
    console.log('bucket:', BUCKET_NAME, 'file-path:', fileName);

    var imageBuffer = decodeBase64Image(event.image, context);
    console.log(imageBuffer);

    var params = {Bucket: BUCKET_NAME, Key: DIRECTORY_PATH + fileName, ContentType: imageBuffer.type, Body: imageBuffer.data};

    s3.putObject(params, function(err, data) {
        if (err) {
            console.log(err);
            context.fail('Image upload failed. file=' + DIRECTORY_PATH +  fileName);
        } 
        context.succeed('Image upload success. file=' + DIRECTORY_PATH +  fileName);
    });
};

function decodeBase64Image(dataString, context) {
    var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),
    response = {};

    if (matches.length !== 3) {
        context.fail('Invalid input string');
    }

    response.type = matches[1];
    if (matches[1] != 'image/jpeg') {
        context.fail('image file is not jpeg format.');
    }
    response.data = new Buffer(matches[2], 'base64');

    return response;
}
9
10
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
9
10