send file to an api using guzzle http client - laravel

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)

Related

image not store in database laravel

I want to Create app in laravel that manage my events
i use this code for EventController
public function store(Request $request)
{
$request->validate([
'inviter'=>'max:255',
'date'=>'max:255',
'phone'=>'max:255',
'whatsapp'=>'max:255',
'location'=>'max:255',
'approval'=>'max:255',
'number'=>'max:255',
'description'=>'max:255',
'track'=>'max:255',
]);
$eve = new Event([
'inviter'=> $request->get('inviter'),
'date'=> $request->get('date'),
'phone'=> $request->get('phone'),
'whatsapp'=> $request->get('whatsapp'),
'location'=> $request->get('location'),
'number'=> $request->get('number'),
'approval'=> $request->get('approval'),
'description'=> $request->get('description'),
'track'=> $request->get('track'),
]);
if ($request->hasFile('file')) {
$file = $request->file('file');
$fileName = $file->getClientOriginalName();
$filePath = time() . '.' . $file->getClientOriginalName();
$request->file->move(public_path('uploads/events'), $filePath);
$eventImage = Image::createNew();
$eventImage->filename_path = $filePath;
$eventImage->original_filename = $fileName;
$eventImage->event_id = $eve->id;
$eventImage->save();
}
return redirect(route('event.index'))->with('success','Event Created');
}
but image dont create I think related to event_id when I was testing the code correctly and incorrectly
Try this
$eve = Event::create([
'inviter'=> $request->get('inviter'),
'date'=> $request->get('date'),
'phone'=> $request->get('phone'),
'whatsapp'=> $request->get('whatsapp'),
'location'=> $request->get('location'),
'number'=> $request->get('number'),
'approval'=> $request->get('approval'),
'description'=> $request->get('description'),
'track'=> $request->get('track'),
]);

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',
...
]);

Laravel file upload s3 Multipart

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();
}
}
```

How to delete old picture after new one uploaded

I have this in my Controller which handles image upload
public function updateProfileImage(Request $request)
{
$user = auth('api')->user();
$image = $request->input('image'); // image base64 encoded
preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
$image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
$image = str_replace(' ', '+', $image);
$imageName = 'profile' . time() . '.' . $image_extension[1];
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->except('image') + [
'profilePicture' => $imageName
]);
return [
//'Message' => "Success",
'profilePhoto' => $user['profilePicture']
];
}
How can i delete the old picture from the directory after new one has been uploaded.
You can delete the image with Storage::delete() method (https://laravel.com/docs/7.x/filesystem#deleting-files). So, get the image before you update, then delete when it's ok to do:
$oldImage = $user->profilePicture;
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->except('image') + [
'profilePicture' => $imageName
]);
Storage::disk('public')->delete($oldImage);
return [
//'Message' => "Success",
'profilePhoto' => $user['profilePicture']
];
PS: I'm not sure if the profilePicture attribute is the same of your storage. Anyway, make any adjustment to match if needed.

Can Anyone Check This Image Upload Code In Laravel?

I wrote this Code For Image Upload but I do not know if it is secure, or not. Is There any issue or vulnerability in this code??
if($request->hasFile('image')){
$AllowedImages = ['jpeg', 'jpg', 'png'];
$AllowedImageTypes = ['image/jpeg', 'image/png'];
$image = $request->image;
$ImageNameWithExtension = $image->getClientOriginalName();
$ImageName = pathinfo($ImageNameWithExtension, PATHINFO_FILENAME);
$ImageExtension = $image->getClientOriginalExtension();
$ImageType = $image->getMimeType();
$ImageLocalPath = $image->getPathName();
$ImageSize = $image->getSize();
$ImageError = $image->getError();
$ImageNewName = sha1(md5($ImageName)).''.sha1(time()).'.'.$ImageExtension;
if(in_array($ImageType, $AllowedImageTypes) && in_array($ImageExtension, $AllowedImages) && getimagesize($ImageLocalPath) && ($ImageError === 0) && ($ImageSize <= 2000000)){
if($ImageType == 'image/jpeg' && ( $ImageExtension == 'jpeg' || $ImageExtension == 'jpg')){
$img = imagecreatefromjpeg($ImageLocalPath);
imagejpeg( $img, $ImageNewName, 100);
}
elseif($ImageType == 'image/png' && $ImageExtension == 'png'){
$img = imagecreatefrompng($ImageLocalPath);
imagepng( $img, $ImageNewName, 9);
}
imagedestroy($img);
try
{
$StoreImage = $image->storeAs('public/Upload/', $ImageNewName);
if(!$StoreImage){
throw new customException('File Upload Failed');
}
}
catch(customException $e){
session()->flash('File_Error', $e->errorMessage());
return back();
}
}
else{
session()->flash('File_Error', 'Image Validation Error Found');
return back();
}
}
else{
return back();
}
Consider this refactor for your code, it will help make your code cleaner.
public function store(Request $request)
{
$record = Model::create( $this->validateRequest() ); // this can insert other data into your database. In the db table, initially set the image related fields to nullable
$this->storeFile($record); // this will check if the request has a file and update the image related fields accordingly, else it will remain blank as it is nullable by default
return 'all data is saved';
}
private function validateRequest(){
return request()->validate([
'type' => 'nullable',
'image'=> request()->hasFile('image') ? 'mimes:jpeg,jpg,png|max:2000' : 'nullable', // 2000 means a maximum of 2MB
'other_field_1' => 'required',
'other_field_2' => 'required',
'other_field_3' => 'required'
]);
}
private function storeFile($record){
if( request()->hasFile('image') ){
$record->update([
'type' => request()->file->extension(),
'image' => request()->file->store('uploads/files', 'public') // The file will be hashed by default. public is used as second argument so you can access the uploaded file via your public folder
]);
}
}
This is check for file in the request, validate the file and other data, upload the file into storage folder.
You can use this code, for upload image :
In Request file :
public function rules()
{
return [
'image' => 'required|mimes:jpeg,jpg,png|max:50000'
],
}
And in your controller :
public function uploadImage(YourRequestClass $request){
$image = $request->file('image');
try{
$order=new Order();
if (!file_exists('upload/' . $image)) {
$currentDate = Carbon::now()->toDateString();
$imageName = $currentDate . '-' . uniqid() . '.' . $image->getClientOriginalExtension();
if (!file_exists('upload/')) {
mkdir('upload/', 0777, true);
}
$image->move('upload/', $imageName);
$order->image = $imageName;
}
$order->save();
return back();
} catche(\Exception $e){
Log::error($e);
return back();
}
}

Resources