Michael Cool Michael Cool - 9 days ago 6
PHP Question

Upload to AWS S3 failing

I'm trying to upload a file from my Wordpress application to a S3 bucket by Ajax:
Somehow, I don't get an answer and the script fails with a 500 error when applying the 'putObject' method.

app/ajax.php

require_once 's3/start.php'
//wp_die(var_dump($s3)); Seems to be fine
$upload = $s3->putObject([
'Bucket' => $config['s3']['bucket'],
'Key' => 'video,
'Body' => fopen( $_FILES['file']['tmp_name'], 'r' ),
'ACL' => 'public-read',
]);
if ($upload) {
wp_die('Uploaded');
} else {
wp_die('Upload Error');
}


app/s3/start.php

use Aws\S3\S3Client;
require 'aws/aws-autoloader.php';
$config = require('config.php');
$s3 = new S3Client([
'key' => $config['s3']['key'],
'secret' => $config['s3']['secret'],
'region' => $config['s3']['region'],
'version' => 'latest',
]);


app/s3/aws

Latest version of the official AWS SDK for PHP


SOLUTION
The credentials in app/start.php where not assigned correctly when initialising the $s3 object. That's how it must look like

$s3 = S3Client::factory([
'region' => $config['s3']['region'],
'version' => 'latest',
'credentials' => [
'key' => $config['s3']['key'],
'secret' => $config['s3']['secret']
]
]);

Answer

If you upload a file, you should use SourceFile instead of Body.

Example code:

$result = $s3->putObject(array(
        'Bucket'       => $bucket,
        'Key'          => $keyname,
        'SourceFile'   => $filepath,
        'ContentType'  => 'text/plain',
        'ACL'          => 'public-read',
        'StorageClass' => 'REDUCED_REDUNDANCY',
        'Metadata'     => array(    
            'param1' => 'value 1',
            'param2' => 'value 2'
        )
    ));

More info from here - http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpPHP.html