Rams
Rams

Reputation: 74

how to upload files to s3 public bucket without credentials form client side javascript

We'd like to use Javascript AWS SDK to upload files to S3, but without using credentials at all. Uploading using credentials works

We have a bucket which has the permissions of anyone that can upload and download files when i am trying to upload i'm getting this error

message: "No credentials to load"

mycode :

var bucket = new AWS.S3({params: {Bucket: 'bucketName'}});

 var params = {Key: 'data.txt', Body: "kkkkkkkkkkkk"};

bucket.putObject(params, function (err, data) {
alert(err)

});

Upvotes: 2

Views: 2488

Answers (1)

Rob Allsopp
Rob Allsopp

Reputation: 3528

If you have set read/write permissions for all users and your bucket's cors configuration allows PUT requests you should be able to simply do it with ajax:

function httpReq(method, url, data, successCB, errorCB) {
    var xhr = new XMLHttpRequest();

    xhr.addEventListener('load', function () {
        if (xhr.status == 200) {
            successCB(xhr.response);
        } else {
            errorCB({status: xhr.status, response: xhr.response});
        }
    });

    xhr.open(method, url, true);
    xhr.send(data);
}

httpReq('PUT', 'http://yourBucket.s3.amazonaws.com/yourKey', file, function (response) {
    console.log('Upload Successful', response);
}, function (error) {
    console.error(error);
});

Upvotes: 1

Related Questions