Mark Bordelon
Mark Bordelon

Reputation: 123

Post to folder under a public S3 Bucket

I can successfully post a file object via AJAX in client javascript code from my browser to the ROOT of an s3bucket, using this code:

function upload_file(path, fileObj) {
 var fd = new FormData();
 fd.append('key', fileObj.name);
 fd.append('acl', 'bucket-owner-full-control');
 fd.append('Content-Type', fileObj.type);
 fd.append("file",fileObj);

 return $.ajax({
    type : 'POST',
    url : path,
    data : fd,
    processData: false,  // Don't process the data
    contentType: false,  // Don't set contentType
    success: function(json) { console.log('Upload complete!') },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log('Upload error: ' + XMLHttpRequest.responseText);
    }
 });
}

The destination is a test-only temporary(!) globally public S3 bucket configured as follows:

public settings

acl

bucket policy

cors

My problem is that I cannot post to any folder below the root of this bucket. Concretely put, doing this...

upload_file('https://s3-us-west-2.amazonaws.com/bucket.example.com/', fileObj)

results in a successful upload to root bucket.

However doing this...

upload_file('https://s3-us-west-2.amazonaws.com/bucket.example.com/sounds/', fileObj)

returns this error from S3:

Upload error: 
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>MethodNotAllowed</Code>
<Message>The specified method is not allowed against this resource.</Message>
<Method>POST</Method> 
<ResourceType>OBJECT</ResourceType> 
<RequestId>DC6AA872FC4F96B4</RequestId>
<HostId>/AOtAuVcXnRZrQD7Rs+EmpZ2H5YDs5TPgEjmvMpVqSdZuPbnTtE/nh4p/Fgad8v00VQ93RKer8g=</HostId>
</Error>

Since only posting to the subfolder is the problem, I assume my code is correct and that I have misconfigured my folder. What am I missing? My intent after overcoming this problem is to proceed to a more traditional pre-signed URL approach, but still wanted to get the bucket permissions sorted first.

Upvotes: 0

Views: 509

Answers (1)

Michael - sqlbot
Michael - sqlbot

Reputation: 179114

 fd.append('key', fileObj.name);

The object key is were you specify the full path to the file, without a leading slash. The only thing that needs to be different is this line:

fd.append('key', 'sounds/' + fileObj.name);

Upvotes: 2

Related Questions