I want to upload an image from a mobile app and send that file to Laravel API then, I want to send that image to an external API for getting information from pictures. In the controller I have the following code:
public function processImage(Request $request): JsonResponse
{
$request->validate([
'image' => 'image|mimes:jpeg,jpg,png,gif'
]);
$file = $request->file('image');
$filePath = $file->store('temp');
ProcessImageJob::dispatch($filePath);
$jobStatusId = 1;
return response()->json(compact('jobStatusId'));
}
In ProcessImageJob I call the API like this:
$client = new Client();
$response = $client
->post($uploadUrl, [
'headers' => $this->authHeaders,
'multipart' => [
[
'name' => 'files',
'contents' => fopen($this->image, 'r'),
'headers' => [ 'Content-Type' => 'image/jpeg']
],
]
]);
$response = json_decode($response->getBody()->getContents(), true);
when I request, it gives in the queue terminal this error: fopen(temp/XLCeHZJqkmwtyIhJ75rgDNTbXIhrlmncsvqTvvkD.jpg): Failed to open stream: No such file or directory how to fix this error? I appreciate any help.
P.S: For Laravel app, I use sail for docker.
Related
I am trying to create Video ad Campaigns using LinkedIn API. I am using Laravel, Guzzle and I have followed steps given in documentation to upload video
Initialize Upload for Video
Upload the Video
Finalize Video Upload
On Initialization I receive success response with multiple upload Urls depending on the file size. Using these uploadUrl I am making request to upload the file chunk using Guzzle but in response it is throwing INternal server error 500. I understand it can be server error but not sure if that raised to any header, param or token.
Please help If anyone has faced similar issue and got resolved. I am sharing the response of the initialize upload and request being made using Guzzle.
Doc Link
Response of Initialize APi
{#1344 // app/Services/LinkedIn/LinkedInCampaignService.php:328
+"value": {#1324
+"uploadUrlsExpireAt": 1669664693370
+"video": "urn:li:video:C4D10AQGwksU16dn3Zw"
+"uploadInstructions": array:2 [
0 => {#1325
+"uploadUrl": "https://www.linkedin.com/dms-uploads/C4D10AQGwksU16dn3Zw/uploadedVideo?sau=aHR0cHM6Ly93d3cubGlua2VkaW4uY29tL2FtYnJ5L2FtYnJ5LXZpZGVvLz94LWxpLWFtYnJ5LWVwPUFRTE9OS2RwQmlCOS1BQUFBWVM2bndCNTd1MTR1Yjh5bVVKQ1BERDhFcVhIN1hxcXl1OHBiM3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
+"uploadToken": ""
}
}
Calling Upload Urls
public function uploadChunkedVideo($fileName, $uploadInstructions)
{
try {
$fileHandler = fopen(storage_path('app') . '/' . $fileName, 'r');
$client = new Client();
$uploadPartIds = [];
foreach ($uploadInstructions as $instruction) {
$chunkedUpload = $client->put($instruction->uploadUrl, [
'headers' => [
'Content-Type' => 'application/octet-stream',
'Authorization' => 'Bearer ' . $this->accessToken,
'LinkedIn-Version' => config('services.linkedIn.version'),
],
'multipart' => [
[
'name' => $fileName,
'contents' => fread($fileHandler, $instruction->lastByte - $instruction->firstByte),
]
],
]);
//Push etag
$uploadPartIds[] = $chunkedUpload->getHeader('ETag')[0];
}
} catch (\GuzzleHttp\Exception\ServerException $e) {
dd($e->getResponse()->getBody()->getContents());
}
}
This worked for me.
$fileHandler = fopen(storage_path('app') . '/' . $fileName, 'r');
$client = new Client();
$uploadPartIds = [];
foreach ($uploadInstructions as $instruction) {
$chunkedUpload = $client->put($instruction->uploadUrl, [
'headers' => [
'Content-Type' => 'application/octet-stream',
'Authorization' => 'Bearer ' . $this->accessToken,
'LinkedIn-Version' => config('services.linkedIn.version'),
],
'body' => fread($fileHandler, $instruction->lastByte - $instruction->firstByte),
]);
//Push etag
$uploadPartIds[] = $chunkedUpload->getHeader('ETag')[0];
info($uploadPartIds);
}
return $uploadPartIds;
Hi I am trying to send an image. The documentation states that I can send a file using multipart/form-data.
Here is my code:
// I checked it, there really is a file.
$file = File::get(Storage::disk('local')->path('test.jpeg')) // it's the same as file_get_contents();
// Here I use the longman/telegram-bot library.
$serverResponse = Request::sendPhoto([
'chat_id' => $this->tg_user_chat_id,
'photo' => $file
]);
// Here I use Guzzle because I thought that there might be an
// error due to the longman/telegram-bot library.
$client = new Client();
$response = $client->post("https://api.telegram.org/$telegram->botToken/sendPhoto", [
'multipart' => [
[
'name' => 'photo',
'contents' => $file
],
[
'name' => 'chat_id',
'contents' => $this->tg_user_chat_id
]
]
]);
Log::info('_response', ['_' => $response->getBody()]);
Log::info(env('APP_URL') . "/storage/$url");
Log::info('response:', ['_' => $serverResponse->getResult()]);
Log::info('ok:', ['_' => $serverResponse->getOk()]);
Log::info('error_code:', ['_' => $serverResponse->getErrorCode()]);
Log::info('raw_data:', ['_' => $serverResponse->getRawData()]);
In both cases, I get this response:
{\"ok\":false,\"error_code\":400,\"description\":\"Bad Request: invalid file HTTP URL specified: Wrong URL host\"}
Other download methods (by ID and by link) work. Can anyone please point me in the right direction?
Using the php-telegram-bot
library, sendPhoto can be used like so:
<?php
require __DIR__ . '/vendor/autoload.php';
use Longman\TelegramBot\Telegram;
use Longman\TelegramBot\Request;
// File
$file = Request::encodeFile('/tmp/image.jpeg');
// Bot
$key = '859163076:something';
$telegram = new Telegram($key);
// sendPhoto
$chatId = 000001;
$serverResponse = Request::sendPhoto([
'chat_id' => $chatId,
'photo' => $file
]);
The trick is to use Request::encodeFile to read the local image.
I try to send the file via GuzzleHTTP from my application to external API, I make it like this:
public function storeImagesInAmazon(Request $request) {
$uploadFilePath = 'some/endpoint';
$file = $request->file('file');
$client = new Client();
$response = $client->request('POST', $uploadFilePath, [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'multipart/form-data',
],
'multipart' => [
[
'name' => 'file',
'contents' => $file
]
]
]);
$result = json_decode($response->getBody(), true);
return [
'hashedID' => $result['hashedID']
];
}
The error I get is:
Server error: POST some/endpoint resulted in a 500 Internal Server Error response:\n
Errorerror while processing file: Failed to process file: part was null
I tested it via Postman, adding key = 'file', value = 'some_file.pdf' in Body form-data, I am sure file is correct, I mean it isn't damaged, I tried to post different files large one, a small one, pdf or jpg/png.
But I still have this issue and I can't find a solution for this.
I found this solution Guzzle form_params not accepting array
what I'm trying to say is, you need $option as your next param like in that post
$response = $client->post('api', $options);
and that $option is where your headers or multipart or other options goes as per documentation. i already tried using $options and its worked in my case.
I am posting some data from my laravel app to another plain PHP page I have on my local server. The status code returned by Guzzle says it was successful but I am unable to access it. How can I do this?
I've tried using the Post method to retrieve value but no luck
Guzzle Function:
$client = new Client();
$response = $client->request('POST', 'http://localhost/testApp/guzTest.php',
[
'form_params' => [
'amnt' => 75
],
'allow_redirects' => true
]);
echo $response->getStatusCode();
Page Receiving POST DATA:
<?php
if (!empty($_POST['amnt'])) {
echo $_POST['amnt'];
}else
echo 'not found';
?>
I expect to be able to access the amount posted via post method but nothing is yielded.
Try somthing like that .
$client = new Client();
$response = $client->request('POST', 'http://localhost/testApp/guzTest.php',
[
'form_params' => [
'amnt' => 75
],
'allow_redirects' => true
]);
$contents = $response->getBody()->getContents();
$contents = json_decode($contents,true);
return ($contents);
On page Receiving POST DATA:
Response should be like this
return response()->json([
'status' => 'SUCCESS',
'code' => '200',
], 200);
I am trying to upload a file using the Microsoft Graph API. It seems to upload OK, but when trying to open the file I am told that it can not be opened.
Here's the relavent part of my PHP code. I've using Guzzle to make the requests.
$data = file_get_contents($_FILES['foo']['tmp_name']);
$guzzle = new GuzzleHttp\Client();
$sent_options = [
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'text/plain'
],
'form_params' => [
base64_encode($data)
]
];
$guzzle->put($url, $sent_options);
OK, so I've worked it out... for anyone else with the same problem, here's the solution.
$data = file_get_contents($_FILES['foo']['tmp_name']);
$guzzle = new GuzzleHttp\Client();
$sent_options = [
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'text/plain'
],
'body' => $data
];
$guzzle->put($url, $sent_options);