[SOLVED] Multipart Upload using High-Level Abstractions

| | 2 min read

Amazon S3 provides API for multipart upload of large files. Multipart upload allows you to upload a large object as a set of small parts/portion of the object's data. You can upload these small object parts independently. If transmission of any part does not succeed, you can retransmit it without affecting other parts. Amazon S3 combines all the parts and make a single object after all the parts are uploaded.

Advantages of Multipart Upload :

  • Increases performance
  • Quick recovery from any issues like network problems
  • Once you initiate a multipart upload there is no expiry; you must explicitly complete or abort the multipart upload
  • We can upload an object without knowing the size of the object in advance

We can Upload Object in PHP Using two Different Ways:

  1. Using high level abstractions
  2. Using low level API

Now let us look at the PHP High-Level Abstractions for Multipart Upload. This is the simple file upload method. For this upload we need the following:

  1. Download AWS SDK for PHP
  2. Download and install composer
  3. Create an amazon account

Let us look at a simple example:

require 'vendor/autoLoad.php';
use Aws\Common\Exception\MultipartUploadException;
use Aws\S3\Model\MultipartUpload\UploadBuilder;
use Aws\S3\S3Client;

$bucket_name = 'NAME OF THE AMAZON BUCKET NAME';
$object_name  = 'OBJECT NAME';
						
// Instantiate the client.
$s3 = S3Client::factory(array 
  ('key' =>'ACCESS_KEY',
   'Secret' => 'SECRET_KEY',
  )
);

// Prepare the upload parameters.
$uploader = UploadBuilder::newInstance()
  ->setClient($s3)
  ->setSource('/path/to/large/file.mov')
  ->setBucket($bucket)
  ->setKey($keyname)
  ->build();

// Perform the upload. Abort the upload if something goes wrong.
try {
    $uploader->upload();
    echo "Upload complete.\n";
} catch (MultipartUploadException $e) {
    $uploader->abort();
    echo "Upload failed.\n";
    echo $e->getMessage() . "\n";
}

We will get Access Key and Secret Key after creating Amazon account. Hope this helps. Please feel free to get in touch with us for any queries.