Laravel file upload s3 Multipart - laravel

how do I integrate the multipart upload of s3? I am uploading to s3 and everything works. just I want to refactor the code to S3 multipart upload because the files are too large on the server
// Amazon checking folder
$directory = 'Case/'. $caseDir;
foreach ($request->file('fileslab') as $s3file) {
// Getting request names & extension
$s3patientFirstName = $request->patient_firstname;
$s3patientLastName = $request->patient_lastname;
$s3SavedOrigName = $s3file->getClientOriginalName();
$SendFileToS3 = $s3patientFirstName . '_' . $s3patientLastName . '_' . time() . $s3SavedOrigName;
$contents = file_get_contents($dbfile->getRealPath());
$path = Storage::disk('s3')->put($directory. '/' .$SendFileToS3, $contents);
if (!Storage::disk('s3')->exists($directory)){
Storage::disk('s3')->makeDirectory($directory);
$path = Storage::disk('s3')->put( $directory. '/' . $SendFileToS3, $contents );
}else{
$path = Storage::disk('s3')->put( $directory. '/' .$SendFileToS3, $contents);
}
The Amazon SK Example is below:
require 'vendor/autoload.php';
use Aws\Common\Exception\MultipartUploadException;
use Aws\S3\MultipartUploader;
use Aws\S3\S3Client;
$bucket = '*** Your Bucket Name ***';
$keyname = '*** Your Object Key ***';
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-east-1'
]);
// Prepare the upload parameters.
$uploader = new MultipartUploader($s3, '/path/to/large/file.zip', [
'bucket' => $bucket,
'key' => $keyname
]);
// Perform the upload.
try {
$result = $uploader->upload();
echo "Upload complete: {$result['ObjectURL']}" . PHP_EOL;
} catch (MultipartUploadException $e) {
echo $e->getMessage() . PHP_EOL;
}

I fixed it.
foreach ($request->file('fileslab') as $s3file) {
$directory = 'Case/'. $caseDir;
$contents = fopen($s3file, 'rb');
$s3patientFirstName = $request->patient_firstname;
$s3patientLastName = $request->patient_lastname;
$s3SavedOrigName = $s3file->getClientOriginalName();
$SendFileToS3 = $s3patientFirstName . '_' . $s3patientLastName .
'_' . time() . $s3SavedOrigName;
$disk = Storage::disk('s3');
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-west-1'
]);
$uploader = new MultipartUploader($s3, $contents, [
'bucket' => $_ENV['AWS_BUCKET'],
'key' => $SendFileToS3,
]);
try {
$result = $uploader->upload();
} catch (MultipartUploadException $e) {
return $e->getMessage();
}
}
```

Related

send file to an api using guzzle http client

after uploading an image in web system a i want to push the image to another web system b.i am using guzzle http client to push and save the image in system b.i have been able to save the image in system a but when it reaches the part to push and save to system b an error that i have set to show when there is an error on uploading the image.here is my function to save the image on system a
public function productSavePicture(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'product_id' => 'required',
]);
if ($validation->fails()) {
throw new \Exception("validation_error", 19);
}
$product_details = product::where('systemid', $request->product_id)->first();
if (!$product_details) {
throw new \Exception('product_not_found', 25);
}
if ($request->hasfile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension(); // getting image extension
$company_id = Auth::user()->staff->company_id;
if (!in_array($extension, array(
'jpg', 'JPG', 'png', 'PNG', 'jpeg', 'JPEG', 'gif', 'GIF', 'bmp', 'BMP', 'tiff', 'TIFF'))) {
return abort(403);
}
$filename = ('p' . sprintf("%010d", $product_details->id)) . '-m' . sprintf("%010d", $company_id) . rand(1000, 9999) . '.' . $extension;
$product_id = $product_details->id;
$this->check_location("/images/product/$product_id/");
$file->move(public_path() . ("/images/product/$product_id/"), $filename);
$this->check_location("/images/product/$product_id/thumb/");
$thumb = new thumb();
$dest = public_path() . "/images/product/$product_id/thumb/thumb_" . $filename;
$thumb->createThumbnail(
public_path() . "/images/product/$product_id/" . $filename,
$dest,
200);
$systemid = $request->product_id;
$product_details->photo_1 = $filename;
$product_details->thumbnail_1 = 'thumb_' . $filename;
$product_details->save();
// push image to system on saving
$client = new \GuzzleHttp\Client();
$url = "http://systemb/api/push_image";
$response = $client->request('POST',$url,[
'headers' => [ ],
'multipart' => [
[
'name' => $filename,
'contents' => file_get_contents($product_details->getPath()),
],
],
]);
} else {
return abort(403);
}
} catch (\Exception $e) {
if ($e->getMessage() == 'validation_error') {
return '';
}
if ($e->getMessage() == 'product_not_found') {
$msg = "Error occured while uploading, Invalid product selected";
}
{
$msg = "Error occured while uploading picture";
}
$data = view('layouts.dialog', compact('msg'));
}
return $data;
}
i am getting the error "Error occured while uploading picture" but the error is saved in systema but its unabe to be pushed in systemb..i havent understood where i have gone wrong with my code base but i guess that part on guzzle isnt being executed because the data is being saved in systema but its unable to be pushed to systemb.what might be the issue here
Your class Product doesnt have the method getPath() declared
file_get_contents($product_details->getPath())
Change it so it uses the path you used above that line
file_get_contents(public_path() . "/images/product/$product_id/".$filename)

Sending an image with HTTP POST

Recently I wanted to separate my project in different services to I wanted to make blogs independent from the project.
In the first project i have written this code. I want to send the data that i get from the form to another API http://127.0.0.1:100/api/saveBlog
public function update(Request $request, $blog)
{
if (!$blog instanceof Blog) {
$blog = $this->getById($blog);
}
$response = Http::post("http://127.0.0.1:100/api/saveBlog",[
'name' => $request->input('name'),
'description' => $request->input('description'),
'name' => $request->input('name'),
'photto' => $request->file('photto')
]);
dd($response->status());
}
In the API service i am trying to read the data
Route::post("/saveBlog",function (Request $request){
$blog = new Blog();
$blog->name = $request->input('name');
$blog->description = $request->input('description');
$blog->name = $request->input('name');
$main = $request->file('photto');
$fileName = microtime() . '.' . $main->getClientOriginalExtension();
$img = Image::make($main->getRealPath());
$img->resize(400, 400);
$img->stream();
Storage::disk('local')->put('public/blogs/' . $fileName, $img, 'public');
$blog->image_path = "/storage/blogs/" . $fileName;
return $blog->save();
});
But i am getting 500 status error and blog is not being saved in database.
I think the problem is with $request->file('photto')
ANY IDEA?
check whether image exist in request like below
if($request->has('photto')){
$main = $request->file('photto');
$fileName = microtime() . '.' . $main->getClientOriginalExtension();
$img = Image::make($main->getRealPath());
$img->resize(400, 400);
$img->stream();
Storage::disk('local')->put('public/blogs/' . $fileName, $img, 'public');
$blog->image_path = "/storage/blogs/" . $fileName;
}
Updates
$photo = fopen(public_path('/storage/filename'), 'r');
$response = Http::
attach('photo', $photo)
->post($url, [
'param_1' => 'param_1 contents',
...
]);

Change directory for uploading image

How can I change the directory of the uploaded images.
I want to upload it in the App/public/files folder.
My code here:
public function update(Request $request, Organigramme $organigramme)
{
$id = $organigramme->id;
$organigramme = Organigramme::find($id);
$organigramme->matricule = $request->input('matricule');
if ($request->has('profile_image'))
{
$image = $request->file('profile_image');
$name = str_slug($request->input('matricule'));
$folder = '/uploads/images/';
$filePath = $folder . $name. '.' . $image->getClientOriginalExtension();
$this->uploadOne($image, $folder, 'public', $name);
$organigramme->profile_image = $filePath;
$organigramme->save();
}
return view( 'admin.organigrammes.show', compact('organigramme'));
}
public function uploadOne(UploadedFile $uploadedFile, $folder = null, $disk = 'public', $filename = null)
{
$name = !is_null($filename) ? $filename : str_random(25);
$file = $uploadedFile->storeAs($folder, $name.'.'.$uploadedFile->getClientOriginalExtension(), $disk);
return $file;
}
In the config/filesystems file add a new save path.For example:
'images' => [
'driver' => 'local',
'root' => base_path().'/app/public/files',
],
In the code itself, use the following code to save:
Storage::disk('images')->put($path, $image);

laravel livewire intervention images

I am trying to use Intervention image with Livewire to reduce the sizes and I am not succeeding. They can guide me or tell me if Livewire may not allow it.
I am trying to pass this methodology:
foreach ($this->imagenes as $pathGaleria) {
$imgUrl = $pathGaleria->store('imagenesPropiedades');
$img = imgPropiedades::create([
'url' => $imgUrl,
'property_id' => $this->propiedadId
]);
to this other way:
foreach ($this->imagenes as $pathGaleria) {
$imgUrl = $pathGaleria->store('imagenesPropiedades');
Image::make($pathGaleria)->resize(1200, null, function ($constraint) {
$constraint->aspectRatio();
})
->save($imgUrl);
$img = imgPropiedades::create([
'url' => $imgUrl,
'property_id' => $this->propiedadId
]);
}
but the page remains blank. Thank you.
I found this today, may work for you
https://gist.github.com/daugaard47/659984245d31b895d00ee5dcbdee44ec
+
$images = Collection::wrap($request->file('file'));
$images->each(function ($image) use ($id) {
$basename = Str::random();
$original = $basename . '.' . $image->getClientOriginalExtension();
$thumbnail = $basename . '_thumb.' . $image->getClientOriginalExtension();
ImageManager::make($image)
->fit(250, 250)
->save(public_path('/images/' . $thumbnail));
$image->move(public_path('/images/'), $original);
Model::create([
]);
});

Twitter OAUTH and Codeigniter

I'm trying to display tweets on a website built on codeigniter but can't seem to pull in the user tweets. To do this, I'm pulling the following script into my header as an include and then printing the tweet in the appropriate section with the code below. I've already set up the access tokens and consumer keys as well. Any ideas on why this is working?
Include file in header
<?php
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$oauth_access_token = "ACCESS TOKEN HERE";
$oauth_access_token_secret = "ACCESS TOKEN SECRET HERE";
$consumer_key = "CONSUMER KEY HERE";
$consumer_secret = "CONSUMER KEY SECRET HERE";
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
$base_info = buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
// Make Requests
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json, false);
$latest_tweet = $twitter_data[0];
?>
Print tweet
<span class="tweet">"<?php if(!empty($latest_tweet)){echo $latest_tweet->text;} else{echo "Welcome to Time Equities!";} ?>"</span>

Resources