John Davidson

php - AWS S3 displaying a file on the client browser

0 comments
Message:


I am trying to use AWS to store all files from my app there. I was successfully able to upload them to the bucket, but I am not able to retrieve the object to show it to the user. I am getting an error "You cannot call GetObject on the service resource." I am not sure what is wrong? I thought it was permission issues? but if so how come I can upload the file?


Here is what I have


function aws_file_upload($key,$file)
{

$aws = aws();

// Get a resource representing the S3 service.
$s3 = $aws->s3;
$bucket = $s3->bucket('my-bucket-name');

try{
$result = $object = $bucket->putObject([
'Key' => $key,
'Body' => fopen($file, 'r'),
]);
$status = 'OK';

}catch(Exception $e){
$status = 'error';
}

return $status;
}

function aws_file_get($key)
{
$aws = aws();
$s3 = $aws->s3;
$result = $s3->getObject([
'Bucket' => 'my-bucket-name',
'Key' => $key
]);

// Display the object in the browser.
header("Content-Type: {$result['ContentType']}");
echo $result['Body'];

}
$key = 'Cases/my-file.pdf';
$file_name = 'my-file.pdf';
$res = aws_file_upload($key,$file_name);/// this will put the file into the AWS bucket

$result = aws_file_get($key);/// this will through the error


My Answer:
when trying to display the file on the client browser. Can you please help me with the code to retrieve and display the file from AWS S3?

Here is a sample code snippet in PHP that you can use to retrieve and display a file from AWS S3 on the client browser:

php

require 'vendor/autoload.php';

use Aws\S3\S3Client;

// Set your AWS credentials
$bucket = 'your-bucket-name';
$key = 'your-file-key';
$region = 'your-region';
$accessKeyId = 'your-access-key-id';
$secretAccessKey = 'your-secret-access-key';

// Create an S3 client
$s3 = new S3Client([
'version' => 'latest',
'region' => $region,
'credentials' => [
'key' => $accessKeyId,
'secret' => $secretAccessKey
]
]);

// Get the object from S3
$result = $s3->getObject([
'Bucket' => $bucket,
'Key' => $key
]);

// Display the file on the client browser
header("Content-Type: {$result['ContentType']}");
echo $result['Body'];

?>


Make sure to replace 'your-bucket-name', 'your-file-key', 'your-region', 'your-access-key-id', and 'your-secret-access-key' with your actual AWS S3 bucket name, file key, region, access key ID, and secret access key respectively.

This code will retrieve the file from the specified bucket and key in AWS S3 and display it on the client browser with the correct content type.

Rate this post

3 of 5 based on 7304 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us