【问题标题】:Get AWS S3 Object with spaces in filename获取文件名中带有空格的 AWS S3 对象
【发布时间】:2019-04-01 23:01:22
【问题描述】:

我正在尝试使用 SDK for PHP 从 AWS S3 下载对象。

$filename = "filename with spaces in it.jpg";

$src = "path/from/bucket-root/".$filename;

$result = S3Client->getObject([

    'Bucket' => 'my-bucket-name',
    'Key' => $src
]);

当我运行这个时,我得到一个错误:

Error executing "GetObject" ... GET filename%20with%20spaces%20in%20it.jpg resulted in a 404 Not Found response:

S3 客户端正在对空格进行编码,但无法解析路径。

我已经尝试了以下所有方法:

$filename = urlencode("filename with spaces in it.jpg");
$filename = urldecode("filename with spaces in it.jpg");
$filename = addslashes("filename with spaces in it.jpg");
$filename = str_replace(' ','+',"filename with spaces in it.jpg");

还有几种组合 - 我现在只是在墙上扔屎。

我的关键路径和存储桶名称/路由是正确的,因为我能够成功获取文件名中没有空格的对象。

如何获取文件名中有空格的对象?

【问题讨论】:

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


    【解决方案1】:

    它实际上不需要用任何东西替换空格,这是工作代码

    <?php
    require 'aws/aws-autoloader.php';
    use Aws\S3\S3Client;
    use Aws\S3\Exception\S3Exception;
    
    $bucket = 'avitest29oct2018';
    $keyname = 'hello there.txt';
    
    $s3 = new S3Client([
      'version' => 'latest',
      'region'  => 'us-west-2',
      'credentials' => false
    ]);
    
    try {
      // Get the object.
      $result = $s3->getObject([
        'Bucket' => $bucket,
        'Key'    => $keyname
      ]);
    
      // Display the object in the browser.
      header("Content-Type: {$result['ContentType']}");
      echo $result['Body'];
    } catch (S3Exception $e) {
       echo $e->getMessage() . PHP_EOL;
    }
    
    ?>
    

    注意:-

    1. 移除 credentials' => false 以读取私有 S3 文件
    2. 我将在几天后删除我的 S3 文件,替换上面代码中的存储桶名称和键名

    不知道是不是和你用的aws sdk有关,有多种方式可以安装aws sdk for php,你是怎么安装的?我使用了3rd method(使用 zip 文件)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 2015-07-11
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 2019-12-16
      • 2015-11-22
      相关资源
      最近更新 更多