I am posting an image to my API using "guzzlehttp/guzzle": "6.3". When I post image to my API, I get false when I check for the file using hasFile(). Could it be that the file is not being submitted to my API?
Controller
$client = new Client();
$url = 'http://localhost:9000/api';
$path = 'app/public/images/';
$name = '94.jpeg';
$myBody['fileinfo'] = ['449232323023'];
$myBody['image'] = file_get_contents($path.$name);
$request = $client->post($url, ['form_params' => $myBody]);
$response = $request->getBody();
return $response;
API
if (!$request->hasFile('image')) {
return response()->json([
'message' => 'No file',
'photo' => $request->hasFile('image'),
'photo_size' => $request->file('image')->getSize()
]);
}
You'll need to add your form_params to the multipart array:
// untested code
$client = new Client();
$endpoint = 'http://localhost:9000/api';
$filename = '94.jpeg';
$image = public_path('images/' . $filename);
$request = $client->post($endpoint, [
'multipart' => [
[
'name' => 'fileinfo',
'contents' => '449232323023',
],
[
'name' => 'file',
'contents' => fopen($image, 'r'),
],
],
]);
$response = $request->getBody();
return $response;
Related
here is my code in controller
constructor code in
private $drive;
public function __construct(\Google_Client $client)
{
$this->middleware(function ($request, $next) use ($client) {
$accessToken = [
'access_token' => auth()->user()->token,
'created' => auth()->user()->created_at->timestamp,
'expires_in' => auth()->user()->expires_in,
'refresh_token' => auth()->user()->refresh_token
];
$client->setAccessToken($accessToken);
if ($client->isAccessTokenExpired()) {
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
}
Auth::user()->update([
'token' => $client->getAccessToken()['access_token'],
'expires_in' => $client->getAccessToken()['expires_in'],
'created_at' => $client->getAccessToken()['created'],
]);
}
$client->refreshToken(auth()->user()->refresh_token);
$this->drive = new \Google_Service_Drive($client);
return $next($request);
});
}
the method that uploading files to drive I think the problem is this method
function createFile($file, $parent_id = null){
$fileName = FileStorage::find($file)->first();
$name = pathinfo(asset('uploadedfiles/' . $fileName->filenames));
$meta = new \Google_Service_Drive_DriveFile([
'name' => $name['basename'],
'parent' => '1GJ3KC-vsBrLAtlwUYgOvm7AjrtIXb4t-',// Parent Folder ID
]);
$content = File::get('uploadedfiles/' . $fileName->UniqueFileName);
$mime = File::mimeType('uploadedfiles/' . $fileName->UniqueFileName);
$file = $this->drive->files->create($meta, [
'data' => $content,
'mimeType' => $mime,
'uploadType' => 'multipart',
'fields' => 'id',
]);
}
where is the problem in my code? Any help would be appreciated.
The reason it is going to root is that you are not setting a parent folder.
You are using the parameter parent when in fact the parameter you should be using is parents and the value should be an array. parent is just getting ignore since its not a valid parameter
change
$meta = new \Google_Service_Drive_DriveFile([
'name' => $name['basename'],
'parent' => '1GJ3KC-vsBrLAtlwUYgOvm7AjrtIXb4t-',// Parent Folder ID
]);
to
$meta = new Drive\DriveFile(array(
'name' => $name['basename'],
'parents' => array('1GJ3KC-vsBrLAtlwUYgOvm7AjrtIXb4t-')
));
I'm working on a laravel apis which is consumed by a mobile application. The issue is i am using this library ( https://github.com/kreait/firebase-php ) to send FCM to device Ids. I have 10k device ids in my db. Issue is the code is implemented badly and it gets timedout after 1 minute. I need advice what is the best way to overcome this issue?
I have written this code:
// General Notification
$deviceTokens = PushDevices::all()->pluck( 'device_id' )->toArray();
if ( $request->hasFile( 'file' ) || $request->file ) {
try {
$request->validate( [
'image' => 'image|mimes:jpeg,jpg|max:2048|size:400'
] );
$originName = $request->file( 'file' )->getClientOriginalName();
$fileName = pathinfo( $originName, PATHINFO_FILENAME );
$extension = $request->file( 'file' )->getClientOriginalExtension();
$fileNames = time() . '.' . $extension;
$request->file( 'file' )->move( public_path( 'storage/notification' ), $fileNames );
$notiData = [
'title' => $request->title,
'body' => $request->body,
'imageurl' => $fileNames
];
// Create a copy in database for notifications.
NotificationTable::create( $notiData );
// Initiate token with https
$notification = [
'title' => $validation->safe()->only( 'title' )['title'],
'body' => $validation->safe()->only( 'body' )['body'],
'image' => 'https://example.com/storage/notification/' . $fileNames
];
$data = [
'first_key' => 'First Value',
'second_key' => 'Second Value',
];
$response[] = '';
foreach ( $deviceTokens as $object ) {
// $message = CloudMessage::new()->withTarget('token', $object)->withNotification($notification);
$message = CloudMessage::fromArray( [
'token' => $object,
'notification' => $notification
] );
try {
$sendReport = $this->messaging->send( $message );
$response[] = $sendReport;
} catch ( \Throwable $e ) {
$response[] = $e;
}
}
return response()->json( [ 'status' => true, 'response', $response ], Response::HTTP_ACCEPTED );
} catch ( \Throwable $th ) {
return response()->json( [
'status' => false,
'message' => $th->getMessage()
], 500 );
}}
$batchSize = 1000;
$deviceGroups = array_chunk($deviceTokens, $batchSize);
$notification = ['title' => $validation->safe()->only( 'title' )['title'], 'body' => $validation->safe()->only( 'body' )['body'],];
NotificationTable::create( $notification );
$data = ['first_key' => 'First Value', 'second_key' => 'Second Value',];
$response = array();
foreach ( $deviceTokens as $object ) {
$message = CloudMessage::new()->withTarget( 'token', $object )->withNotification( $notification )->withData( $data );
try {
$sendReport = $this->messaging->send( $message );
$response[] = $sendReport;
} catch ( MessagingException|FirebaseException $e ) {
$response[] = $e;
}
}
return response()->json( [ 'status' => true, 'response', $response ], Response::HTTP_ACCEPTED );
I want to send messages to all 10k devices but am unable to understand how to do it.
I want to Post data with matrix, color, and source (upload file) to an API with lumen laravel.
here my code
generateMotif(data, token) {
var path = `motif`;
var formData = new FormData();
formData.append("matrix", data.matrix);
formData.append("color", data.color);
formData.append("source", data.file);
return axios.post(`${API_URL}/${path}`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
token: token,
},
params: {
token: token,
},
})
.catch((error) => {
if (error.response) {
return Promise.reject({
message: error.response.data.error,
code: error.response.status
});
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
// The request was made but no response was received
console.log(error.request);
throw error;
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
// console.log(error.response.data);
throw error;
}
});
},
here my API controller code
public function generateMotif(Request $request)
{
$all_ext = implode(',', $this->image_ext);
$this->validate($request, [
'matrix' => 'required',
'color' => 'required',
'source' => 'required|file|mimes:' . $all_ext . '|max:' . $this->max_size,
]);
$model = new UserMotif();
$file = $request->file('source');
$store = Storage::put('public/upload', $file);
dd($store);
$client = new Client;
try {
$response = $client->request('POST', 'http://localhost:9000/motif', [
'multipart' => [
[
'name' => 'matrix',
'contents' => $request->input('matrix'),
'headers' => [ 'Content-Type' => 'multipart/form-data']
],
[
'name' => 'color',
'contents' => $request->input('color'),
'headers' => [ 'Content-Type' => 'multipart/form-data']
],
[
'name' => 'img_file',
// 'contents' => fopen(storage_path('app/' . $store), 'r'),
'contents' => $request->file('source'),
'filename' => $file->getClientOriginalName(),
'headers' => [ 'Content-Type' => 'multipart/form-data']
],
]
]);
$images = $data->getBody()->getContents();
$filePath = '/public/' . $this->getUserDir();
$fileName = time().'.jpeg';
if ($result = Storage::put($filePath . '/' . $fileName, $images)) {
$generated = $model::create([
'name' => $fileName,
'file_path' => $filePath,
'type' => 'motif',
'customer_id' => Auth::id()
]);
return response()->json($generated);
}
} catch (RequestException $e) {
echo $e->getRequest() . "\n";
if ($e->hasResponse()) {
echo $e->getResponse() . "\n";
}
return response($e->getResponse());
}
return response()->json(false);
}
There are no errors in my controller because I'm not found any error or issues when compiling the code. Response in my controller terminal is 200.
The results that I want from this code are an image. Because in this API, it will process an image and give new image response. But when I'm posting an image, the results are scripts like this.
{data: "<script> Sfdump = window.Sfdump || (function (doc)…re><script>Sfdump("sf-dump-1493481357")</script>↵", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
I don't know what's wrong in my code, but you have any suggestion for my code, please help me. Any suggestions will be very helpful to me.
I want to develop a website using ReactJS as frontend and 2 API projects both develop in Lumen Laravel as backend. I want to post an image from the frontend to API A, and API A will post the image again to API B, API B will process the image using Matlab.
In my cases, when I'm posting the image to API A, the image will not post the image again to API B. But when I change my code, post the image to API B, the image processed by API B. I don't know why API A can't post Image again from frontend to API B.
Here my code.
PostImage.js
postImage(data, token) {
const path = `image`;
const formData = new FormData();
formData.append("file", data.file);
formData.append("matrix", data.matrix);
formData.append("color", data.color);
return axios.post(`${API_A}/${path}`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
token: token,
},
params: {
token: token,
},
})
.catch((error) => {
if (error.response) {
return Promise.reject({
message: error.response.data.error,
code: error.response.status
});
} else if (error.request) {
console.log(error.request);
throw error;
} else {
console.log('Error', error.message);
throw error;
}
});
}
and API A
public function postImage(Request $request)
{
$all_ext = implode(',', $this->image_ext);
$this->validate($request, [
'matrix' => 'integer',
'color' => 'integer',
'file' => 'required|file|mimes:' . $all_ext . '|max:' . $this->max_size,
]);
$model = new UserImage();
$file = $request->file('file');
$store = Storage::put('public/upload', $file);
dd($store);
try {
$response = $this->client->request('POST', 'http://apiB/imageProcess', [
'multipart' => [
[
'name' => 'matrix',
'contents' => (int) $request->get('matrix', 2),
'headers' => [ 'Content-Type' => 'multipart/form-data']
],
[
'name' => 'color',
'contents' => (int) $request->get('color', 1),
'headers' => [ 'Content-Type' => 'multipart/form-data']
],
[
'name' => 'img_file',
'contents' => fopen(storage_path('app/' . $store), 'r'),
'filename' => $file->getClientOriginalName(),
'headers' => [ 'Content-Type' => 'multipart/form-data']
],
]
]);
$image = $response->getBody()->getContents();
$filePath = '/public/' . $this->getUserDir();
$fileName = time().'.jpeg';
if ($result = Storage::put($filePath . '/' . $fileName, $image)) {
$generated = $model::create([
'name' => $fileName,
'file_path' => $filePath,
'type' => 'motif',
'customer_id' => Auth::id()
]);
return response()->json($generated);
}
} catch (RequestException $e) {
echo $e->getRequest() . "\n";
if ($e->hasResponse()) {
echo $e->getResponse() . "\n";
}
return response($e->getResponse());
}
return response()->json(false);
}
API B
public function processImage(Request $request){
$msg = $this->validateParam($request);
if($msg != ''){
return response()->json(array(
'message'=>$msg.' is not valid'
), 200);
}
ini_set('max_execution_time', 1500);
$sourceFolderPath = 'public/img_src/param_temp/before/';
$resultFolderPath = base_path('public\img_src\param_temp\after');
$matrix = $request->input('matrix');
$color = $request->input('color');
$image = $request->file('img_file');
$extension = image_type_to_extension(getimagesize($image)[2]);
$nama_file_save = $sourceFileName.$extension;
$destinationPath = base_path('public\img_src\param_temp\before'); // upload path
$image->move($destinationPath, $nama_file_save);
$sourceFile = $destinationPath .'\\' . $nama_file_save;
$resultFile = $resultFolderPath .'\\'. $resultFileName.'.jpg';
$command = "matlab command";
exec($command, $execResult, $retval);
if($retval == 0){
$destinationPath = base_path('public\img_src\param_temp\after');
$sourceFile = $destinationPath .'\\' . $resultFileName.'.jpg';
$imagedata = file_get_contents($sourceFile);
if(!$imagedata) return $this->errorReturn();
$base64 = base64_encode($imagedata);
$data = base64_decode($base64);
return response($data)->header('Content-Type','image/jpg');
}
return $this->errorReturn();
}
the image saved in API A, but not processed to API B
I don't know where is wrong in my code, but if you have any suggestion, It will be very helpful for me
I have:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use GuzzleHttp\Client;
class GetBlahCommand extends Command {
protected $name = 'blah:blah';
protected $description = "name";
public function handle()
{
$client = new Client();
$res = $client->request('GET', 'https://someapi.com', [
'api_key' => ['privatekey']
]);
echo $res->getStatusCode();
}
}
But the param api_key isn't being passed along.
How can I get this to work?
I have adjusted my code, but now I am getting NULL returned:
$ndbnos = [
'ndbno' => '01009'
];
$client = new Client(['base_uri' => 'https://soemapi.com']);
$res = $client->request('GET', '/', [
'query' => array_merge([
'api_key' => 'somekey'
], $ndbnos)
])->getBody();
$res = json_decode($res);
var_dump($res);
I figured it out:
public function handle()
{
$ndbnos = [
'ndbno' => '01009'
];
$client = new Client(['base_uri' => 'https://someapi.com']);
$res = $client->request('GET', '', [
'query' => array_merge([
'api_key' => 'somekey',
'format' => 'json'
], $ndbnos)
]);
print_r(json_decode($res->getBody()));
}
You can be do it by the following way:
public function handle()
{
$client = new Client(['base_uri' => 'https://someapi.com/']);
$res = $client->request('GET', '/', [
'headers' => [
'api_key' => 'YOUR_KEY'
]
]);
}
I thought it's a header parameter. If it's a form input you can do it by the following way:
public function handle()
{
$client = new Client(['base_uri' => 'https://someapi.com/']);
$res = $client->request('GET', '/', [
'query' => [
'api_key' => 'YOUR_KEY'
]
]);
}