Kirk Beard Kirk Beard - 9 days ago 5
PHP Question

How to set Content-Disposition with AWS PHP SDK v2 and CopyObject?

I'm using the AWS PHP SDK v2.x to copy objects between S3 buckets using the following code:

<?php
try {
self::$aws->copyObject(array(
'Bucket' => $target_bucket,
'Key' => $target_key,
'CopySource' => $source_bucket . '/' . $source_key,
'Content-Disposition' => 'attachment',
//'Content-Disposition' => 'attachment; filename="' . basename($target_key) . '"'
//'ContentDisposition' => 'attachment'
//'ContentDisposition' => 'attachment; filename="' . basename($target_key) . '"'
));
} catch (Aws\S3\Exception\S3Exception $e) {
echo 'error';
}


The file is copied to the S3 bucket without any errors, but I'm unable to set the the
Content-Disposition
in order to force the browser to download the file rather than stream it. I've tried a few options (commented out above) but nothing seem to work.

I've even attempted to pass the value in the
Metadata
array even though the documentation says otherwise but the AWS Console lists the
Content-Disposition
under the Metadata section.

If I manually change the
Content-Disposition
in the AWS Console then the browser downloads the file as expected.

So, how can I pass the value to the S3 object correctly? Can I pass it at all using the
CopyObject()
method?

Answer

The CopyObject operation is tricky, IMO. I think the missing piece of the puzzle for you is the MetadataDirective parameter. Try the following:

$s3Client->copyObject(array(
    'Bucket'     => $target_bucket,
    'Key'        => $target_key,
    'CopySource' => $source_bucket . '/' . $source_key,
    'ContentDisposition' => 'attachment; filename="'.basename($target_key).'"',
    'MetadataDirective'  => 'REPLACE',
));

Note: The code is in this post is also licensed under version 2.0 of the Apache License.

Comments