kai ogita
kai ogita

Reputation: 136

how download image and put S3 in lambda nodejs

'use strict';
var https = require('http');
var aws = require('aws-sdk');
var fs = require('fs');

aws.config.update({
    accessKeyId: 'id',
    secretAccessKey: 'key',
    region: 'ap-northeast-1'
});

var s3bucket = new aws.S3();
var bucketName = "bukcetName"

exports.handler = (event, context, callback) => {    

https.get("URL.jpg", function(res, body){

    body = new Buffer(res.body, 'binary');
    var params = {
        Bucket:bucketName,
        Key: "testLambda",
        Body: body,
        ACL: 'public-read'
    };
    s3bucket.upload(params, function(err, data) {
            context.done(null, 'Finished UploadObjectOnS3');

    });
});

};

APIGateway ---> lambda

i want download from URL in lambda and that content put S3.

i cant get binary data from URL but i can any data put any directory in S3 thanks help.

Upvotes: 2

Views: 3662

Answers (1)

Geander
Geander

Reputation: 388

I've made some changes to your code to make it work better.
-You do not need the 'fs'.
-The correct method is 'putObject' instead of 'upload'.
Thank you!

'use strict';
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
var http = require('http');

aws.config.update({
  accessKeyId: 'id',
  secretAccessKey: 'key',
  region: 'ap-northeast-1'
});

var s3bucket = new AWS.S3();
var bucketName = "bukcetName";

exports.handler = (event, context, callback) => {    

  http.get("URL.jpg", function(res){
    var imageData = ''; 

    res.setEncoding('binary');

    res.on('data', function(chunk){
      imageData += chunk;
    });

    res.on('end', function(){

      var params = {
        Bucket: bucketName,
        Key: "testLambda",
        Body: new Buffer(imageData, 'binary'),
        ACL: 'public-read'
      };    

      s3.putObject(params, function(err, data) {
        if (err) console.log(err, err.stack);
        else     console.log(data);
        context.done(null, 'Finished UploadObjectOnS3');
      });       

    });

  });

};

Upvotes: 5

Related Questions