How do I show an image from my Amazon S3 on my website?

前端 未结 3 1738
孤独总比滥情好
孤独总比滥情好 2020-12-30 12:21

I have my pictures on Amazon S3. The pictures are private and not public so I can not show them with a direct link s3.amazonaws/bucket_name/key_name/image_name.jpg

相关标签:
3条回答
  • 2020-12-30 12:45

    For those who needs this behavior with AWS SDK v3, if you directly call getObjectUrl with '+10 minutes' as third parameter, it will always return the plain URL. That's because the method changed. To get the pre-signed link, do the following:

    //Get an instance of S3 Client. This is one one to do it:
    $s3Client = new S3Client([
        'version'     => 'latest',
        'region'      => 'us-west-2', //Region of the bucket
        'credentials' => array(
            'key' => 'YOUR-ACCOUNT-KEY',
            'secret'  => 'YOUR-ACCOUNT-SECRET',
        )
    ]);
    
    //Get a command to GetObject
    $cmd = $s3Client->getCommand('GetObject', [
        'Bucket' => 'YOUR-BUCKET-NAME',
        'Key'    => 'YOUR-FILE-KEY'
    ]);
    
    //The period of availability
    $request = $s3Client->createPresignedRequest($cmd, '+10 minutes');
    
    //Get the pre-signed URL
    $signedUrl = (string) $request->getUri();
    

    Ref: https://docs.aws.amazon.com/aws-sdk-php/v3/guide/service/s3-presigned-url.html

    0 讨论(0)
  • 2020-12-30 12:52

    Easiest thing to do is make them public in s3, at least read-only.

    If you don't want them to be public on s3, for whatever reason, you could add a cloudfront distribution that will serve the images from your s3 bucket, and you can give cloudfront access to the files, without making the images public in s3.

    This link shows you how to do that:

    http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html

    0 讨论(0)
  • 2020-12-30 13:04

    If you don't want to make your file public, here is the procedure.

    1. ensure your S3 bucket is private. Only authenticated and authorised calls are allowed to get your objects

    2. on the server side, when rendering the page, generate links to S3 object that include a signature. The signature will be computed from your access and secret key and will tell S3 that the call must be authorised

    S3 Signed URL are easy to generate from our SDK. For PHP, just check the doc at http://docs.aws.amazon.com/aws-sdk-php/guide/latest/service-s3.html#creating-a-pre-signed-url

    1. in the web page, when the user will click a signed URL, the browser will be directed to S3. S3 will verify the signature and - when correct - will get the object
    0 讨论(0)
提交回复
热议问题