简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM