M gowda
M gowda

Reputation: 203

How can I upload the image to AWS S3

How to access that key name <code>pin_img</code> in my post API

pin.js

function uploadPinMedia(req, res, next) {

    var s3 = new AWS.S3({
        accessKeyId: 'AKIAIUCBE3TQGL6ATPBA',
        secretAccessKey: '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',
        Bucket: 'mapery-v2'
    });

    var data = {
        Bucket: 'mapery-v2',
        Key: 'upload-v2',
        Body: req.files.pin_img
    };

    s3.putObject(data, function(err, media_res) {
        if(err) 
            console.log('error uploading data', media_res);
        console.log(media_res);
    });
    
}
I am trying to upload an image to s3 bucket from postman, but it seems to be the form data req.files.pin_img I am passing is not correct. Am I wrong anywhere ??

Upvotes: 4

Views: 12230

Answers (2)

Ajay
Ajay

Reputation: 197

I am triggering/Invoking Upload to S3 Bucket Lambda function from another lambda function using Promise in nodejs.

Note:- To Invoke target lambda from source , we need to create a invoke policy [Under IAM->Policy] and attach it to Lambda Role. enter image description here enter image description here

async function uploadToS3 (indexName){
await new Promise((resolve, reject) => {

        console.log(" Uploading to S3 ");
        
        //Lambda Parameter
        let lambda_params = {
            FunctionName: 'Library_Update_S3_Bucket', // Invoke lambda function 
         
            InvocationType: 'RequestResponse',
            LogType: 'Tail',
            Payload : JSON.stringify( { name : "ElasticsearchConfig.json", Body : 
               {"tableName" : "documents" , indexName } })
            };
         
         const lambdaS3Result = lambda.invoke(lambda_params ,  function(err, results) 
          {
            if (err) {
              console.log("Upload Failed :- ",err.message);
             response = {
                statusCode: 500,
                body: {message:"Upload to S3 Failed"}
                }
              
              reject(err);
            }
            else{
                console.log("Uploaded Successfully to S3");
                console.log("Results is :", results.Payload.statusCode )
                 response = {
                    statusCode: 200,
                    body: {message:"Done Uploading to S3"}
                    }
                    
                resolve(results);
            }
         });

  });
  }

Lambda Function Name :- Library_Update_S3_Bucket

enter image description here

let response = {};

exports.handler = async (event) => {
// TODO implement

var params = {Bucket : 'pe-library', Key: event.name, Body: 
JSON.stringify(event.Body), ContentType: "application/json"};
console.log(params);
try {
    await s3.upload (params).promise();
    response =  { 
        statusCode: 200,
        body: "Uploaded Successfully"
    }
} catch (err){
    console.log(err)
    response =  {
        statusCode: 500,
        body: "Upload Failed"
    }
}


return response;
};

Upvotes: 0

shivshankar
shivshankar

Reputation: 2135

below works for me. make sure you have correct config. bucket. you'll found uploaded image using https://appname.s3-accelerate.amazonaws.com/aws_test.jpg

const AWS = require('aws-sdk');
AWS.config.update({
        accessKeyId: process.env.AWS_KeyId,
        secretAccessKey: process.env.AWS_secret,
        // region:process.env.AWS_region  
});

const s3 = new AWS.S3({   signatureVersion: 'v4',  })
var photoBucket = new AWS.S3({
    params: {
        Bucket: 'bucket'
    }
})
photoBucket.upload({
        ACL: 'public-read', 
        Body: fs.createReadStream('./test.jpg'), 
        // file upload by below name
        Key: 'aws_test.jpg',
        ContentType: 'application/octet-stream' // force download if it's accessed as a top location
},(err, response)=>{
    console.log(err, response)
});

Upvotes: 8

Related Questions