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
CodePudding user response:
You need to create an s3 client.
Here is some sample code from Creating and Using Amazon S3 Buckets with the AWS SDK for PHP Version 3 - AWS SDK for PHP:
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
$s3Client = new S3Client([
'profile' => 'default',
'region' => 'us-west-2',
'version' => '2006-03-01'
]);
$result = $s3Client->putObject([
'Bucket' => $bucket,
'Key' => $key,
'SourceFile' => $file_Path,
]);
CodePudding user response:
For anyone wanting an answer here was my solution.
$aws = aws();
$s3 = $aws->s3;
$bucket = $s3->bucket('my-bucket-name');
$result = $bucket->object($key)->get();
header("Content-Type: {$result['ContentType']}");
echo $result['Body'];