dovhpmnm31216 2018-10-29 03:18
浏览 181

获取带有文件名空格的AWS S3对象

I'm trying to download an object from AWS S3 using the SDK for PHP.

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

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

$result = S3Client->getObject([

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

When I run this, I get an error:

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

The S3 client is encoding the spaces but then not able to resolve the path.

Ive tried all of the following:

$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");

And several combinations - Im just throwing turds at the wall at this point.

My key path and bucket name/route are correct since I am able to successfully get object without spaces in the filename.

How do I grab this object with spaces in the filename?

  • 写回答

1条回答 默认 最新

  • 普通网友 2018-10-29 05:10
    关注

    It actually works without replacing spaces with anything, here is the working code

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

    Note:-

    1. Remove credentials' => false to read private S3 file
    2. I will take down my the S3 file in few days, replace bucket name and keyname in the above code

    Not sure if it is related to the aws sdk you used, there are various ways you can install aws sdk for php, how did you install it? i used 3rd method (using zip file)

    评论

报告相同问题?

问题事件

  • 专家修改了标签 8月18日

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大