1 year ago
#354099
Superveci
What is the correct way to pass a form with an image to GuzzleHTTP
I want to send a form which includes an image to my API. In my controller I have this:
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Http\Response
*/
public function store( BrandCreateRequest $request )
{
$params = [
'form_params' => $request->except( 'logo', '_token' )
];
if( $request->has( 'logo' ) ){
$file = $request->file( 'logo' );
$params[ 'multipart' ] = [
[
'name' => 'logo',
'filename' => $file->getClientOriginalName(),
'contents' => Psr7\Utils::tryFopen( $file->getRealPath(), 'r' ),
],
];
}
$request_url = new RequestURL( 'brands', 'post', $params );
return $request_url->getResponse();
}
But when I send the request, I get this message:
"json_encode error: Type is not supported"
So I am guessing the problem is the file part of the array $params. Can someone guide me on the correct way to do it?
This is the RequestURL class:
class RequestURL
{
public string $endpoint;
public string $method;
public array $params;
public array $headers;
public mixed $response = null;
public int $code = 200;
public string $message = '';
/**
* @param string $endpoint
* @param string $method
* @param array $params
* @param array $headers
*/
public function __construct( string $endpoint, string $method = 'post', array $params = [], array $headers = [] )
{
$this->endpoint = $endpoint;
$this->method = $method;
$this->params = $params;
$this->headers = $this->makeHeaders( $headers );
$this->send();
}
/**
* @return void
*/
private function send()
{
$client = new Client( [ 'base_uri' => config( 'superveci.api' ) ] );
try{
$response = $client->request( $this->method, $this->endpoint, [
'json' => $this->params,
'headers' => $this->headers,
'verify' => false,
] );
$this->response = $response;
$this->code = $response->getStatusCode();
}
catch( GuzzleException $e ){
$this->code = $e->getCode();
$this->response = null;
$this->message = $e->getMessage();
}
}
/**
* @return ResponseInterface|null
*/
public function getResponse() : ?ResponseInterface
{
return $this->response;
}
/**
* @param array $headers
*
* @return array
*/
private function makeHeaders( array $headers = [] ) : array
{
$bearer = ( isset( $headers[ 'token' ] ) ) ? $headers[ 'token' ] : request()->cookie( '_token' );
if( $bearer != null ){
$headers[ 'Authorization' ] = 'Bearer ' . $bearer;
}
return array_merge( [ 'Accept' => 'application/json', ], $headers );
}
}
I'm adding the class RequestURL to show how it wraps the GuzzleHttp. Basically the constructor receives the endpoint, the method, the params from the form and the headers. Then it sends the request using GuzzleHttp\Client to get a response.
laravel
guzzle
0 Answers
Your Answer