【问题标题】:AWS PHP SDK v3 check if a file exists already in S3 bucketAWS PHP SDK v3 检查文件是否已存在于 S3 存储桶中
【发布时间】:2019-11-10 09:35:47
【问题描述】:

我正在使用 PHP 和 AWS SDK v3 开发一个项目,我必须通过传递文件名来检查文件是否已经存在。

这是我尝试过的:

来自 HTML 模板:

<html>
    <form id="form" action="check_existing.php" method="post">
        <input type="text" name="fName" >
        <input type="submit" name="submit" value="Submit"><br />
    </form>
</html>

来自 check_existing.php:

include 'create_client.php';
if(isset($_POST["submit"])){            
    $filename = $_POST['fName'];
    $info = $s3->doesObjectExist($bucketName, $filename);
    print($info);
    if ($info)
    {
        echo 'File exists';
    }
    else
    {
    echo 'File does not exists';
    }
}

这是我创建s3 客户端的方式:

$s3 = new Aws\S3\S3Client([
    'region' => $region,
    'version' => 'latest',
    'credentials' => [
        'key'    => $IAM_KEY,
        'secret' => $IAM_SECRET,
    ],
]);

问题:它总是返回File does not exists

【问题讨论】:

  • 对我来说看起来是正确的。我会验证 $s3 是否已正确创建 (print_r($s3);) 并仔细检查 $bucketName$filename 值并确保它们是正确的。
  • print_r($s3); 正确给出响应,这意味着客户端正在工作。我还仔细检查了存储桶和文件名。
  • $region 可以吗?您可以在dashboard 中查看每个桶的区域

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


【解决方案1】:
$s3 = new S3($s3_accesskey, $s3_secretkey); //create s3 object

$info = $s3->getObjectInfo($s3_bucket, $filename); // $filename can be path of file in bucket
if ($info){
    echo 'File exists';
}else{
    echo 'File does not exists';
}

getObjectInfo() 返回信息如下

Array
(
[date] => 1596690179
[time] => 1596651169
[hash] => 1234c1234341a7f2565c108b23b4aaca
[type] => image/jpeg
[size] => 18968
)

【讨论】:

    【解决方案2】:

    你可以试试这个。参考:enter link description here

    $s3 = new AmazonS3();
    $bucket = 'your-bucket' . strtolower($s3->key);
    
    $test = $s3->doesObjectExist($bucket, 'testfile.jpg');
    
    // Success or not? (Boolean, not a CFResponse object)
    var_dump($test); // it will return boolean
    

    【讨论】:

    • 它会抛出一个错误:Fatal error: Uncaught Error: Class 'AmazonS3' not found in /Applications/MAMP/htdocs/s3_php/check_existing.php
    • 嗨@nageennayak,最后一件事var_dump($test) 是如何告诉对象存在的?它是否返回boolean,请编辑您的答案!所以,我会接受的。
    猜你喜欢
    • 2020-11-06
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 2016-11-12
    • 2023-03-14
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多