File upload Amazon S3 on Drupal

Spread the love

I have been searching for upload file to Amazon S3 on Drupal 7.

There’s AWS SDK for Amazon S3 file uploading. It is not difficult to make it worked. Here’s the other post regarding sample uploading script on php.

There are some modules like Composer, Composer Manager, S3FS. But none of them worked in my case. So I decide to make my own module for drupal.

  1. Create one dummy module in custom module folder.
    e.g. fusion_composer folder
  2. Run drush composer command
    drush composer
  3. Create composer.json file with this code in the same module folder
  4. Install composer files associated with AWS service.
    drush composer install
    drush composer update

    This will create vender folder with AWS related content.
    Now you can use this code for production site. You can create this on Dev site and commit then you can use it on production site without install. This is way better than installing composer on production site.

  5. Here’s example file uploading function on test module.
    Amazon S3 sample file upload on Drupal
    Amazon S3 sample file upload on Drupal
    function amazon_s3_sample_file_upload() {
        //S3 configuration
        $module = 'fusion_composer';
        $file = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/vendor/autoload.php";
        $bucket = variable_get('amazons3_bucket');
        $bucket = 'test';
        $client_config = [
            'version'     => 'latest',
            'region'      => 'us-east-1',
            'credentials' => [
                'key'    => variable_get('aws_key'),
                'secret' => variable_get('aws_secret')
            'debug'   => false
        $s3 = Aws\S3\S3Client::factory($client_config); 
        $sample_file_url = '';
        $directory_uri = 'public://tmp/flv_videos';
        $pathinfo = pathinfo($sample_file_url);
        $file_path = $directory_uri.'/'.$pathinfo['basename'];
        $filename = drupal_basename($file_path);
        $real_path = drupal_realpath($file_path);
        $aws_path = date('Y/m/d').'/'.$filename;
        $result = $s3->putObject([
            'Bucket' => $bucket,
            'Key'    => $aws_path,
            'SourceFile' => $real_path,

    So first include autoload.php and set configuration for the bucket and API keys. Download the sample file from url and save to temporary folder. Then upload the file to S3 server.

Works like charm!

Facebook Comments

Published by

Titus Choi

I love technology. Working for information technology. Interested in AVR technology. Playing with RC stuff.