rigaman
rigaman

Reputation: 151

Can't upload images in nodejs using aws-sdk

I've tried using aws-sdk and knox and I get status code 301 trying to upload images. I get status code 301 and message - 'The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint. This works in php.

AWS.config.loadFromPath(__dirname + '/config/config.json');
fs.readFile(source, function (err, data) {
var s3 = new AWS.S3();
    s3.client.createBucket({Bucket: 'mystuff'}, function() {
       var d = {
            Bucket: 'mystuff',
            Key: 'img/test.jpg',
            Body: data,
            ACL: 'public-read'
            };
       s3.client.putObject(d, function(err, res) {
            if (err) {
                console.log("Error uploading data: ", err);
                callback(err); 
            } else {
                console.log("Successfully uploaded data to myBucket/myKey");
                callback(res);   
            }
        });
    });
}); 

Upvotes: 5

Views: 4940

Answers (3)

vincent
vincent

Reputation: 293

I have the same problem with the new SDK and solved it by setting the endpoint option explicitly.

Reference : http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#constructor_details

Snippet:

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

var s3 = new AWS.S3({ endpoint :'https://s3-your-region-varies.amazonaws.com' }),
    myBucket = 'your-bucket-name';

var params = {Bucket: myBucket, Key: 'myUpload', Body: "Test"};

s3.putObject(params, function(err, data) {
    if (err)  {
        console.log(err) 
    } else {
        console.log("Successfully uploaded data to "+myBucket+"/testKeyUpload");
    }
});

Alternatively, you can solve this by setting the region in your config file and you just have to be precise of your region name.

Upvotes: 0

rigaman
rigaman

Reputation: 151

I actually solved this problem. In your config you have to have a region, since my bucket was "US Standard", I left my region blank and it worked. config.json - { "accessKeyId": "secretKey", "secretAccessKey": "secretAccessKey", "region": ""}

go to s3 management console select one of your files and click on proporties - > look at the file link. US standard https://s3.amazonaws.com/yourbucket/ host in your console window yourbucket.s3.amazonaws.com/

us-west-1 https://s3-us-west-1.amazonaws.com/yourbucket/ host in your console window yourbucket.s3-us-west-1.amazonaws.com/

Upvotes: 7

shin73
shin73

Reputation: 66

Did you try .send()?

I can upload to S3 by below code.

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/AWSRequest.html

var s3object = {Bucket: 'mystuff', Key: name, Body : data['data']};
    s3.client.putObject(s3object).done(function(resp){
      console.log("Successfully uploaded data");
    }).fail(function(resp){
      console.log(resp);
    }).send();

Upvotes: 5

Related Questions