how to send a file from one web system to another using guzzle client in laravel - api

i want to send an image from one web system(A) to another web system(B).the image is saved in system(A) and then sent to system(B).am using guzzle http client to achieve this.my api in system (B) works very well as i have tested it in postman.the part i have not understood why its not working is in my system(A) where i have written the guzzle code.i have not seen any error in my system(A) log file but the file isnt sent to system (B).
here is my image save function is system(A).
public function productSavePicture(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'product_id' => 'required',
]);
$product_details = product::where('systemid', $request->product_id)->first();
if ($request->hasfile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension(); // getting image extension
$company_id = Auth::user()->staff->company_id;
$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(B)
$imageinfo = array(
'file' => $filename,
'product_id' => $product_details->id,
);
$client = new \GuzzleHttp\Client();
$url = "http://systemb/api/push_h2image";
$response = $client->request('POST',$url,[
// 'Content-type' => 'multipart/form-data',
'multipart' => [
[
'name' => 'imagecontents',
'contents' => fopen(public_path() . ("/images/product/$product_id/") . $filename, 'r'),
// file_get_contents(public_path("/images/product/$product_id/thumb/thumb_" . $filename)),
'filename' =>$filename
],
[
'name' => 'imageinfo',
'contents' => json_encode($imageinfo)
],
]
]);
}
}
}
i have followed every step in the documentation but still the process isnt working.where might i be making a wrong move?the laravel version of my project is 5.8 and the version of the guzzle http client is 7.4.1

Related

Correct image path to delete from storage laravel 8

I try to delete the old profilepicture in storage file but it is not working.
below is my screenshot of my files
and this is my code in update profile controller.
public function updateProfile(Request $request, User $user)
{
if ($request->hasFile('profilepicture')) {
Storage::delete('/storage/profilepicture' . $user->profilepicture);
$filenameWithExt = $request->file('profilepicture')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('profilepicture')->getClientOriginalExtension();
$fileNameToStore = time() . '.' . $extension;
$path = $request->file('profilepicture')->storeAs('public/profilepicture', $fileNameToStore);
$user->update([
'profilepicture' => $fileNameToStore
]);
}
$user->update([
'name' => $request->name,
'email' => $request->email,
'birth_date' => $request->birth_date,
'section' => $request->section,
'unit' => $request->unit,
'phone' => $request->phone,
]);
return back()->withSuccess('You have successfully update User.');
}
i already tried
Storage::delete('/public/storage/profilepicture/' . $user->profilepicture);
Storage::delete('/storage/profilepicture/' . $user->profilepicture);
Storage::delete('profilepicture/' . $user->profilepicture);
but none of them is working. Or there is any other correct way to do this?
Use class Filesystem instead of Storage, and give it an absolute path like this:
// Declare
use Illuminate\Filesystem\Filesystem;
// Using
$file = 'icon-256x256.png';
$path = public_path('profilepicture/' . $file);
Filesystem::delete($path);
You will delete the file successful!

Rest Unknown Error while uploading image on wordpress media using guzzle

Rest Unknown Error while uploading image on wordpress media using guzzle:
Actually m trying to upload image using guzzle but the wordpress is giving server error that rest upload unknown error ... Please tell what i am doing wrong???
public function store(Request $request)
{
//
$image_path = $request->file('image')->getPathname();
$image_mime = $request->file('image')->getmimeType();
$image_org = $request->file('image')->getClientOriginalName();
$username = '####';
$password = '#######';
$http = new \GuzzleHttp\Client;
$response = $http->POST('websitenameurl/wp2/wp-json/wp/v2/media/',
[
'headers'=>[
'Authorization'=> 'Basic ' . base64_encode( $username . ':' . $password),
'Content-Type' => 'Application/json'
],
'multipart' => [
[
'name' => 'image',
'filename' => $image_org,
'Mime-Type'=> $image_mime,
'contents' => fopen($image_path, 'r' ),
],
],
]);
$result = json_decode((string)$response->getBody(),true);
return $result;
}

laravel view pdf file from s3 in new tab

how to open pdf file from s3 in a new tab ?
the following code download the file .. but i want to view it in the browser
store method in controller
public function store(Request $request)
{
$validated = $request->validate([
'leg_number' => 'required',
'leg_year' => 'required',
'leg_title' => 'required',
'leg_type_id' => 'required',
'leg_published' => 'required',
'file' => 'required',
]);
$name = $request->leg_number . '_' . $request->leg_year . '.pdf';
$path = 'documents/' . $name;
Storage::disk('s3')->put($path, $request->file, 'public');
$validated['leg_path'] = $name;
$document = Legislation::create($validated);
}
show method in controller
public function showLegislation(Legislation $legislation)
{
$content = Storage::disk('s3')->get('documents/' . $legislation->leg_path);
$header = [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="' . $legislation->leg_path . '"'
];
return Response::make($content, 200, $header);
}
route
Route::get('legislation/show/{legislation}', [LegislationController::class, 'showLegislation'])->name('legislation.show');
blade
Finally ... it's internet dwonlaod manager that capture the link and dwonload the file.. if i disable it .. everything works fine

Decode base64 into jpeg and save the image to server

currently i have base 64 value in
$model->test
and i want to decode the base 64 value in controller and save it to database through API here some of my code in controller
i try to decode and cant figure out how to upload it to server and create path
however i try to to pass the $data to getinstance which is not working
public function doSaveStudent(StudentLoanForm $model)
{
$url = API_URL . 'web/apply/student';
$data1 = $model->test;
$decode = base64_decode($data);
$img = file_put_contents('webcam.jpg', $data);
$model->doUploads();
$ktpdetail = UploadedFile::getInstance($model, 'image_ktp');
$data = null;
$data = [
[
'name' => 'univ_name',
'contents' => $model->univ_name
],
[
'name' => 'test',
'contents' =>$model->test
],
];
// dd($model->test);
if ($ktpdetail != null) {
$data[] = [
'name' => 'image_ktp',
'contents' => fopen(Yii::getAlias('#frontend/web/') . $model->image_ktp, 'r'),
'filename' => $ktpdetail->getBaseName() . '.' . $ktpdetail->getExtension()
];
}
if($ktpayahdetail != null){
$data[] = [
'name' => 'foto_ktp_ayah',
'contents' => fopen(Yii::getAlias('#frontend/web/') . $model->foto_ktp_ayah, 'r'),
'filename' => $ktpayahdetail->getBaseName() . '.' . $ktpayahdetail->getExtension()
];
}
if ($kkdetail != null) {
$data[] = [
'name' => 'image_kk',
'contents' => fopen(Yii::getAlias('#frontend/web/') . $model->image_kk, 'r'),
'filename' => $kkdetail->getBaseName() . '.' . $kkdetail->getExtension()
];
i expect to decode the base 64 and upload all the value using yii2 best practice
The yii\web\UploadedFile is used only for files uploaded using file input in forms.
In your case base64_decode($model->test) should give you binary data of image.
Then you have two options what to do with them.
1) You can store them directly into BLOB attribute in database.
$imageModel = new MyImageModel();
$imageModel->data = base64_decode($model->test);
if(!$imageModel->save()) {
throw new \yii\base\Exception("Couldn't save file to db");
}
2) You can save the file with file_put_contents and then store the path to file in your model.
$imageData = base64_decode($model->test);
//the used alias in path is only example.
//The datetime and random string are used to avoid conflicts
$filename = Yii::getAlias(
'#frontend/web/' . date('Y-m-d-H-i-s') .
Yii::$app->security->generateRandomString(5) . '.jpg'
);
if (file_put_contents($filename, $imageDate === false) {
throw new \yii\base\Exception("Couldn't save image to $filename");
}
$imageModel = new MyImageModel();
$imageModel->path = $filename;
if(!$imageModel->save()) {
//delete file if we couldn't save path into db to prevent creating an orphan
unlink($filename);
throw new \yii\base\Exception("Couldn't add $filename to database");
}

Ebay Unsupported API call error upon using GuzzleHttp client v6

I am trying to get sessionid by using ebay Trading API . I am able to get session id successfully by using Curl but as soon as i try to fetch session id via Guzzle Http client, get below error in response from ebay
FailureUnsupported API call.The API call "GeteBayOfficialTime" is
invalid or not supported in this release.2ErrorRequestError18131002
I suppose there's some issues with the way i am using GuzzleHttp client . I am currently using GuzzleHttp v6 and new to this . Below is the code i am using to get session id by calling actionTest function
public function actionTest(){
$requestBody1 = '<?xml version="1.0" encoding="utf-8" ?>';
$requestBody1 .= '<GetSessionIDRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
$requestBody1 .= '<Version>989</Version>';
$requestBody1 .= '<RuName>test_user-TestAs-Geforc-ldlnmtua</RuName>';
$requestBody1 .= '</GetSessionIDRequest>';
$headers = $this->getHeader();
$client = new Client();
$request = new Request('POST','https://api.sandbox.ebay.com/ws/api.dll',$headers,$requestBody1);
$response = $client->send($request);
/*$response = $client->post('https://api.sandbox.ebay.com/ws/api.dll', [
'headers' => $headers,
'body' => $requestBody1
]);*/
echo $response->getBody();die;
}
public function getHeader()
{
$header = array(
'Content-Type: text/xml',
'X-EBAY-API-COMPATIBILITY-LEVEL: 989',
'X-EBAY-API-DEV-NAME: a4d749e7-9b22-441e-8406-d3b65d95d41a',
'X-EBAY-API-APP-NAME: TestUs-GeforceI-SBX-345ed4578-10122cfa',
'X-EBAY-API-CERT-NAME: PRD-120145f62955-96aa-4d748-b1df-6bf4',
'X-EBAY-API-CALL-NAME: GetSessionID',
'X-EBAY-API-SITEID: 203',
);
return $header;
}
Plz suggest the possible shortcoming in the way i am making request . I already tried/modified the guzzle request call by referring various reference site and guzzle official doc but error remained same .
You need to pass an associative array of headers as explained in the documentation.
public function getHeader()
{
return [
'Content-Type' => 'text/xml',
'X-EBAY-API-COMPATIBILITY-LEVEL' => '989',
'X-EBAY-API-DEV-NAME' => '...',
'X-EBAY-API-APP-NAME' => '...',
'X-EBAY-API-CERT-NAME' => '...',
'X-EBAY-API-CALL-NAME' => '...',
'X-EBAY-API-SITEID' => '203',
];
}
In case you are interested there is an SDK available that simplifies the code. An example of how to call GetSessionID is shown below.
<?php
require __DIR__.'/vendor/autoload.php';
use \DTS\eBaySDK\Trading\Services\TradingService;
use \DTS\eBaySDK\Trading\Types\GetSessionIDRequestType;
$service = new TradingService([
'credentials' => [
'appId' => 'your-sandbox-app-id',
'certId' => 'your-sandbox-cert-id',
'devId' => 'your-sandbox-dev-id'
],
'siteId' => '203',
'apiVersion' => '989',
'sandbox' => true
]);
$request = new GetSessionIDRequestType();
$request->RuName = '...';
$response = $service->getSessionID($request);
echo $response->SessionID;