aws

How to Download an S3 File Using a Different Filename

I was recently working on the downloadable files features on the Cinevee platform and noticed that renaming large S3 files (1Gb+) using the AWS SDK S3 client can take up to 5-10 seconds — making the site feel like its frozen or sluggish. So I created a ‘Display Name’ field in our files table to keep track of the public-facing name of the file.

Not only does this beautify our file names to the customer but it speeds up the responsiveness of our platform for admins (usually DB calls are faster than API calls). Before updating, we recognized this introduced a potential disconnect for the customers who would click to download ‘FEATURE FILM 720p HD.m4v’ but end up with a file that was originally named ‘FEATUREFILM_123.m4v’. Luckily, with AWS SDK2, we can download any file in our S3 bucket with a different filename. Let’s get started.

Include AWS SDK

<?
require_once('aws.phar');
use Aws\Common\Aws;
use Aws\S3\S3Client;
$s3Client = S3Client::factory(array(
   'key' => $this->config->item('s3_id'),
   'secret' => $this->config->item('s3_secret')
));
?>

GetObject via getCommand()

<?
$s3_bucket = 'bucket.example.com';
$file_path = 'folder/feature_123456.m4v';
$displayname = 'Feature 720p HD.m4v';
$command = $s3Client->getCommand('GetObject', array(
   'Bucket' => $s3_bucket,
   'Key' => $file_path,
   'ResponseContentDisposition' => 'attachment; filename="'.$displayname.'"'
));
?>

Generate Signed URL & Initiate Download

<?
$signedUrl = $command->createPresignedUrl('+15 minutes');
header('Location: '.$signedUrl);
die();
?>

Notice there aren’t any extra headers we need to send before the redirect — that information is all contained within the $signedUrl. Hope this helps!