获取文件名中包含空格的AWS S3对象

问题描述 投票:0回答:2

我正在尝试使用 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
2个回答
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,您是如何安装的?我使用了第三种方法(使用zip文件)


0
投票

我遇到了这个问题,这解决了它:

$key = str_ireplace(' ', '+', $key);

AWS 将“+”识别为空格,因此只需将“”替换为“+”即可。

© www.soinside.com 2019 - 2024. All rights reserved.