【问题标题】:How to set Content-Disposition with AWS PHP SDK v2 and CopyObject?如何使用 AWS PHP SDK v2 和 CopyObject 设置 Content-Disposition?
【发布时间】:2016-11-24 16:44:39
【问题描述】:

我正在使用AWS PHP SDK v2.x 使用以下代码在 S3 存储桶之间复制对象:

<?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';
}

该文件被复制到 S3 存储桶而没有任何错误,但我无法设置 Content-Disposition 以强制浏览器下载文件而不是流式传输它。我尝试了一些选项(上面已注释掉),但似乎没有任何效果。

我什至尝试传递Metadata 数组中的值,尽管documentation 另有说明,但AWS Console 在元数据部分下列出了Content-Disposition

如果我手动更改AWS Console 中的Content-Disposition,则浏览器会按预期下载文件。

那么,如何正确地将值传递给 S3 对象? 可以我使用CopyObject() 方法来传递它吗?

【问题讨论】:

    标签: php amazon-s3 aws-php-sdk


    【解决方案1】:

    CopyObject 操作很棘手,IMO。我认为您缺少的难题是MetadataDirective 参数。请尝试以下操作:

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

    注意:这篇文章中的代码也是在 Apache 许可证 2.0 版下获得许可的。

    【讨论】:

    • ContentDisposition 只需要指定的“附件”值即可工作,但 MetadataDirective 是缺少的信息。
    • 这很好地设置了 ContentDisposition,但不幸的是破坏了 Content-type。在保留内容类型的同时,最好的方法是什么?
    • @ChadE.:您可以先进行头部请求,然后从现有文件中获取现有的内容类型、元数据或您需要的任何其他信息,并将其/它们包含在您的 copyObject 参数中。我不确定是否有更简单的方法来完成您所需要的。
    猜你喜欢
    • 2018-08-28
    • 2011-04-27
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    相关资源
    最近更新 更多