Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using aws-sdk to upload images to s3 using nodejs

I want to upload images to amazon web server and for that I am using aws-sdk with nodejs.

I am able to upload images to the s3 bucket, but when I click on the URL to access them I get access-denied error.

Here is my configuration

     var AWS = require('aws-sdk');

     //aws credentials
     AWS.config = new AWS.Config();
     AWS.config.accessKeyId = "<access_key>";
     AWS.config.secretAccessKey = "<secret_key>";
     AWS.config.region = "ap-southeast-1";
     AWS.config.apiVersions = {
        "s3": "2006-03-01"
     }

    var s3 = new AWS.S3();

    var bodystream = fs.createReadStream(req.files.pic.path);

    var params = {
        'Bucket': '<bucket_name>',
        'Key': 'uploads/images/' + req.files.pic.name,
        'Body': bodystream,
        'ContentEncoding': 'base64', 
        'ContentType ': 'image/jpeg'
     };

     //also tried with s3.putObject
     s3.upload(params, function(err, data){
        console.log('after s3 upload====', err, data);
     }) 

Images are uploading successfully but their content-type is application/octet. Also I think that there is some permission issue, because when I add a new permission then I am able to download the image but not able to see it.

Can you tell me what is wrong with this configuration and also I want to know the difference between s3.upload and s3.putObject method.

like image 884
Bhushan Goel Avatar asked Oct 30 '15 07:10

Bhushan Goel


1 Answers

In order to specify Content-Type header you need to define Metadata section:

var params = {
    'Bucket': '<bucket_name>',
    'Key': 'uploads/images/' + req.files.pic.name,
    'Body': bodystream,
    'ContentEncoding': 'base64', 
    Metadata: {
        'Content-Type': 'image/jpeg'
    }

 };
like image 61
Vsevolod Goloviznin Avatar answered Oct 15 '22 10:10

Vsevolod Goloviznin