【问题标题】:Uploading file to S3 using presigned URL in PHP使用 PHP 中的预签名 URL 将文件上传到 S3
【发布时间】:2019-01-19 11:15:45
【问题描述】:

我正在使用 PHP 开发一个 Web 应用程序。在我的应用程序中,我需要使用预签名 URL 将文件上传到 AWS S3 存储桶。现在,我可以像这样使用预签名从 S3 存储桶中读取私有文件。

$s3Client = new S3Client([
            'version' => 'latest',
            'region' => env('AWS_REGION', ''),
            'credentials' => [
                'key' => env('AWS_IAM_KEY', ''),
                'secret' => env('AWS_IAM_SECRET', '')
            ]
        ]);

            //GetObject
        $cmd = $s3Client->getCommand('GetObject', [
                'Bucket' => env('AWS_BUCKET',''),
                'Key'    => 'this-is-uploaded-using-presigned-url.png'
            ]);

        $request = $s3Client->createPresignedRequest($cmd, '+20 minutes');


        //This is for reading the image. It is working.
        $presignedUrl = (string) $request->getUri();

当我从浏览器访问$presignedUrl 时,我可以从 s3 获取文件。这是工作。但是现在,我正在将文件上传到 S3。不从 s3 读取文件。通常,我可以像这样将文件上传到 S3。

$client->putObject(array(
    'Bucket' => $bucket,
    'Key'    => 'data.txt',
    'Body'   => 'Hello!'
));

上面的代码没有使用预签名的 URL。但我需要使用预签名的 URL 上传文件。如何,我可以使用预签名的 URL 上传文件。比如我在想的是这样的。

$client->putObject(array(
        'presigned-url' => 'url'
        'Bucket' => $bucket,
        'Key'    => 'data.txt',
        'Body'   => 'Hello!'
    ));

如何上传?

【问题讨论】:

    标签: php amazon-web-services amazon-s3 pre-signed-url


    【解决方案1】:

    您可以通过运行来创建预签名的PutPobject 命令似乎是合理的:

    $cmd = $s3Client->getCommand('PutObject', [
      'Bucket' => $bucket,
      'Key'    => $key
    ]);
    
    $request = $s3Client->createPresignedRequest($cmd, '+20 minutes')->withMethod('PUT');
    

    然后您可能希望使用 PHP 执行 PUT 调用:

    file_put_contents($request->getUri(), 'Hello!', stream_context_create([
      'http' => [ 'method' => 'PUT' ] ]);
    
    

    如果您想创建一个浏览器可以提交的 URL,那么您需要让浏览器将文件作为表单 POST 发送。此 AWS 文档说明了如何创建预签名的 POST 请求字段,然后您需要将其放入 HTML 表单并显示给用户:https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/s3-presigned-post.html

    另外,这个答案可能有用:https://stackoverflow.com/a/59644117/53538

    【讨论】:

    • 我在网络上尝试了很多解决方案,但只有这个对我有用。非常感谢,@Guss。
    猜你喜欢
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 2016-10-12
    • 2021-08-18
    • 2012-04-23
    • 1970-01-01
    相关资源
    最近更新 更多