Multipart Upload using High-Level Abstractions

| | 2 min read

Amazon S3 provide 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 is 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:

  • Increase 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 we can look on to the PHP High-Level Abstractions for Multipart Upload. This is the simple file upload method. For this upload we need following:

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

Now we can look on to the 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. If you need any further assistance, please get in touch with us.