Post request for S3 image file - php

I have a php script to pull an image file from amazon S3 called test.php
if I write the html like this <img src="test.php"> The image appears fine.
However when I try to use a get request and set the SRC of the image it doesnt appear correctly. I eventually want to pass params in using post once this works. On inspecting the src its filled with meta data as if header("Content-type: image") hasnt been set.
$.get( "test.php",function( data ) {
$('#image1').attr('src', data);
});
My test.php script:
require '../vendor/autoload.php';
use Aws\S3\S3Client;
$region = 'us-west-2';
$bucket = 'mybucket';
$key = 'mykey';
$secret = 'mysecret';
$s3Client = new S3Client([
'version' => 'latest',
'region' => $region,
'credentials' => [
'key' => $key,
'secret' => $secret,
],
]);
$result = $s3Client->getObject(array(
'Bucket' => $bucket,
'Key' => 'monkey1.jpg'
));
header("Content-type: image");
// Print the body of the result by indexing into the result object.
echo $result['Body'];
//echo '<img src="'.$result['Body'].'">'

get the object URL temporal and load it to the page
$result = $s3->get_object_url($bucket, 'monkey1.jpg', '1 minute');
from this you can load the image to the page!
echo '<img src="'.$result.'">

This worked for me.
PHP script
$s3Client = new S3Client([
'version' => 'latest',
'region' => $region,
'credentials' => [
'key' => $key,
'secret' => $secret,
],
]);
$s3Client->registerStreamWrapper();
if (file_exists('s3://'.$bucket.'/'.$id.'/'.$filepath)) {
//echo 'It exists!';
$result = $s3Client->getObject(array(
'Bucket' => $bucket,
//'Key' => 'monkey1.jpg'
'Key' => $id.'/'.$filepath
));
header("Content-type: image/*");
// Print the body of the result by indexing into the result object.
echo base64_encode($result['Body']);
}
JS
$('#image').attr('src', 'data:image/*;base64,'+data);

Related

I Unable to move images in S3 bucket from our main server

I want to upload my images in the amazon s3 bucket. My images database uploaded to another web server. I am unable to move it to the S3 bucket. I referred to some solutions from StackOverflow.
Here is my code I have tried:
use \usr\share\php\AWSSDKforPHP\S3;
use \usr\share\php\AWSSDKforPHP\S3\S3Client;
use \usr\share\php\AWSSDKforPHP\S3\Exception\S3Exception;
$bucket = 'cdn.example.com';
$keyname = $newfilename;
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-east-1',
'credentials' => [
'key' => "**********************",
'secret' => "**********************************"
]
]);
try {
// Upload data.
$result = $s3->putObject([
'Bucket' => $bucket,
'Key' => $keyname,
'SourceFile' => $oldfilepath,
'ACL' => 'public-read'
]);
// Print the URL to the object.
echo $result['ObjectURL'] . PHP_EOL;
} catch (S3Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
Showing error in output:
Fatal error: Class 'usr\share\php\AWSSDKforPHP\S3\S3Client' not found in /var/www/html/cron-jobs/shift-img.php on line 35

How Do I Create a Dynamic Keyname Using Php AWS S3 API

Have been testing the latest Php AWS S3 API and I not sure how to dynamically name a keyname when a user uploads a new book, reason being I need to be able to retrieve the uploaded book by XYZ customer. Thanks in advance!
<?php
require 'aws/aws-autoloader.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
//AWS S3 SHITE BELOW
$bucket = 'acmebooks';
//CREATE DYNAMIC KEYNAME??
$keyname = 'RANDOM KEYNAME';
$secret = 'FOOBAR1345';
$credentials = new Aws\Credentials\Credentials($keyname, $secret);
$s3 = new Aws\S3\S3Client([
'version' => 'latest',
'region' => 'us-east-2',
'credentials' => $credentials
]);
try {
// Upload data.
$result = $s3->putObject([
'Bucket' => $bucket,
'Key' => $keyname,
//Body' => 'Hello, world!',
'Body' => 'https://booksrun.com/image-loader/350/https:__images-na.ssl-images-amazon.com_images_I_41sYJq3nAWL.jpg',
'ACL' => 'public-read'
]);
// Print the URL to the object.
echo $result['ObjectURL'] . PHP_EOL;
print_r($result['Body']);
} catch (S3Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
?>
Was overlooking and confusing $keyname which is my unique AWS S3 "Key", for the "Key name" of what is PUT into the AWS S3 Bucket.
FIX BELOW
<?php
require 'aws/aws-autoloader.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
//TEST FOR AWS S3
$key_input = 'jaybookcover1';
//AWS S3 SHITE BELOW
$bucket = 'acmebooks';
//UNIQUE AWS S3 KEYNAME??
$keyname = ' my unique AWS S3 key';
$secret = 'FOOBAR1345';
$credentials = new Aws\Credentials\Credentials($keyname, $secret);
$s3 = new Aws\S3\S3Client([
'version' => 'latest',
'region' => 'us-east-2',
'credentials' => $credentials
]);
try {
// Upload data.
$result = $s3->putObject([
'Bucket' => $bucket,
'Key' => $key_input,
//Body' => 'Hello, world!',
'Body' => 'https://booksrun.com/image-loader/350/https:__images-na.ssl-images-amazon.com_images_I_41sYJq3nAWL.jpg',
'ACL' => 'public-read'
]);
// Print the URL to the object.
echo $result['ObjectURL'] . PHP_EOL;
print_r($result['Body']);
} catch (S3Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
?>

How to fix upload image to s3 using Laravel

I try to upload an image to s3 using Laravel but I receive a runtime error. Using Laravel 5.8, PHP7 and API REST with Postman I send by body base64
I receive an image base64 and I must to upload to s3 and get the request URL.
public function store(Request $request)
{
$s3Client = new S3Client([
'region' => 'us-east-2',
'version' => 'latest',
'credentials' => [
'key' => $key,
'secret' => $secret
]
]);
$base64_str = substr($input['base64'], strpos($input['base64'], ",") + 1);
$image = base64_decode($base64_str);
$result = $s3Client->putObject([
'Bucket' => 's3-galgun',
'Key' => 'saraza.jpg',
'SourceFile' => $image
]);
return $this->sendResponse($result['ObjectURL'], 'message.', 'ObjectURL');
}
Says:
RuntimeException: Unable to open u�Z�f�{��zڱ��� .......
The SourceFile parameter is leading to the path of file to upload to S3, not the binary
You can use Body parameter to replace the SourceFile, or saving the file to local temporary and get the path for SourceFile
Like this:
public function store(Request $request)
{
$s3Client = new S3Client([
'region' => 'us-east-2',
'version' => 'latest',
'credentials' => [
'key' => $key,
'secret' => $secret
]
]);
$base64_str = substr($input['base64'], strpos($input['base64'], ",") + 1);
$image = base64_decode($base64_str);
Storage::disk('local')->put("/temp/saraza.jpg", $image);
$result = $s3Client->putObject([
'Bucket' => 's3-galgun',
'Key' => 'saraza.jpg',
'SourceFile' => Storage::disk('local')->path('/temp/saraza.jpg')
]);
Storage::delete('/temp/saraza.jpg');
return $this->sendResponse($result['ObjectURL'], 'message.', 'ObjectURL');
}
And, if you're using S3 with Laravel, you should consider the S3 filesystem driver instead of access the S3Client manually in your controller
To do this, add the S3 driver composer require league/flysystem-aws-s3-v3, put your S3 IAM settings in .env or config\filesystems.php
Then update the default filesystem in config\filesystems, or indicate the disk driver when using the Storage Storage::disk('s3')
Detail see document here
Instead of SourceFile you have to use Body. SourceFile is a path to a file, but you do not have a file, you have a base64 encoded source of img. That is why you need to use Body which can be a string. More here: https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#putobject
Fixed version:
public function store(Request $request)
{
$s3Client = new S3Client([
'region' => 'us-east-2',
'version' => 'latest',
'credentials' => [
'key' => $key,
'secret' => $secret
]
]);
$base64_str = substr($input['base64'], strpos($input['base64'], ",") + 1);
$image = base64_decode($base64_str);
$result = $s3Client->putObject([
'Bucket' => 's3-galgun',
'Key' => 'saraza.jpg',
'Body' => $image
]);
return $this->sendResponse($result['ObjectURL'], 'message.', 'ObjectURL');
}
A very simple way to uploads Any file in AWS-S3 Storage.
First, check your ENV setting.
AWS_ACCESS_KEY_ID=your key
AWS_SECRET_ACCESS_KEY= your access key
AWS_DEFAULT_REGION=ap-south-1
AWS_BUCKET=your bucket name
AWS_URL=Your URL
The second FileStorage.php
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
//'visibility' => 'public', // do not use this line for security purpose. try to make bucket private.
],
Now come on main Code.
Upload Binary File from HTML Form.
$fileName = 'sh_'.mt_rand(11111,9999).".".$imageFile->clientExtension();;
$s3path = "/uploads/".$this::$SchoolCode."/";
Storage::disk('s3')->put($s3path, file_get_contents($req->file('userDoc')));
Upload Base64 File
For Public Bucket or if you want to keep file Public
$binary_data = base64_decode($file);
Storage::disk('s3')->put($s3Path, $binary_data, 'public');
For Private Bucket or if you want to keep file Private
$binary_data = base64_decode($file);
Storage::disk('s3')->put($s3Path, $binary_data);
I Recommend you keep your file private... that is a more secure way and safe. for this, you have to use PreSign in URL to access that file.
For Pre sign-In URL check this post. How access image in s3 bucket using pre-signed url

How to customize s3 uploaded files url in yii2?

I have used vlaim\fileupload\FileUpload; and yii\web\UploadedFile;
$image = UploadedFile::getInstance($model, 'flag');
$model->flag = new FileUpload(FileUpload::S_S3, [
'version' => 'latest',
'region' => 'us-west-2',
'credentials' => [
'key' => 'KEY',
'secret' => 'SECRET'
],
'bucket' => 'mybucket/uploads/flags/'.$model->code
]);
$uploader = $model->flag;
$model->flag = $uploader->uploadFromFile($image)->path;
In db i'm saving the path. How to customize the url?
Now my url looks like https://s3-us-west-2.amazonaws.com/mybucket%2Fuploads%2Fflags%2Fus/uploads%5C9f%5C7e%5Cc093ad5a.png
I need the url like https://mybucket.s3.amazonaws.com/uploads/flags/us.png
S3 does not have the concept of folders, It is an object store, with key/value pairs. They key for your file would be uploads/flags/us.png
with the PHP SDK it's easy to set the key of the object.
$USAGE = "\n" .
"To run this example, supply the name of an S3 bucket and a file to\n" .
"upload to it.\n" .
"\n" .
"Ex: php PutObject.php <bucketname> <filename>\n";
if (count($argv) <= 2){
echo $USAGE;
exit();
}
$bucket = $argv[1];
$file_Path = $argv[2];
$key = basename($argv[2]);
try{
//Create a S3Client
$s3Client = new S3Client([
'region' => 'us-west-2',
'version' => '2006-03-01'
]);
$result = $s3Client->putObject([
'Bucket' => $bucket,
'Key' => $key,
'SourceFile' => $file_Path,
]);
} catch (S3Exception $e) {
echo $e->getMessage() . "\n";
}
yii2 i think you need to set setFsUrl()
http://www.yiiframework.com/extension/yii2-file-upload/#hh8
setFsUrl(string $url)
(Only for Local mode)
Sets url. For example, if you set path to 'http://static.example.com' file after uploading will have URL http://static.example.com/path/to/your/file
Default to /
php $uploader->setFsPath('http://pathtoyoursite.com');

unable to upload file to sub-folder of main bucket

I am trying to upload error file in AWSS3 but it shows error like "The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint: "test9011960909.s3.amazonaws.com"."
i also specified 'region' => 'us-east-1' but still same error occurs.
it is working when i specify
'Bucket' => $this->bucket,
but i wanted to upload file in sub-folder of main bucket
'Bucket' => $this->bucket . "/" . $PrefixFolderPath,
i already applied approved answer from AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint
but still getting same error, i am using php
Code :
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
class AWSS3Factory {
private $bucket;
private $keyname;
public function __construct() {
$this->bucket = AWSS3_BucketName;
$this->keyname = AWSS3_AccessKey;
// Instantiate the client.
}
public function UploadFile($FullFilePath,$PrefixFolderPath="") {
try {
$s3 = S3Client::factory(array(
'credentials' => array(
'key' => MYKEY,
'secret' => MYSECKEY,
'region' => 'eu-west-1',
)
));
// Upload data.
$result = $s3->putObject(array(
'Bucket' => $this->bucket . "/" . $PrefixFolderPath,
'Key' => $this->keyname,
'SourceFile' => $FullFilePath,
'StorageClass' => 'REDUCED_REDUNDANCY'
));
return true;
// Print the URL to the object.
//echo $result['ObjectURL'] . "\n";
} catch (S3Exception $e) {
echo $e->getMessage() . "\n";
}
}
}
You must create s3 instance in another way, like this:
$s3 = S3Client::factory([
'region' => '',
'credentials' => ['key' => '***', 'secret' => '***'],
'version' => 'latest',
]);
You must add $PrefixFolderPath not to 'Bucket' but to 'Key':
$result = $s3->putObject(array(
'Bucket' => $this->bucket,
'Key' => $PrefixFolderPath . "/" . $this->keyname,
'SourceFile' => $FullFilePath,
'StorageClass' => 'REDUCED_REDUNDANCY'
));

Categories