Как правильно передать форму с изображением в GuzzleHTTP?Php

Кемеровские программисты php общаются здесь
Anonymous
Как правильно передать форму с изображением в GuzzleHTTP?

Сообщение Anonymous »

Я хочу отправить форму, содержащую изображение, в мой API. В моем контроллере у меня есть это:

Код: Выделить всё

/**
* 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();
}
Но когда я отправляю запрос, я получаю следующее сообщение:

Код: Выделить всё

"json_encode error: Type is not supported"
Я предполагаю, что проблема в файловой части массива $params. Может ли кто-нибудь подсказать мне, как правильно это сделать?
Это класс RequestURL:

Код: Выделить всё

    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 );
}
}
Я добавляю класс RequestURL, чтобы показать, как он оборачивает GuzzleHttp. По сути, конструктор получает конечную точку, метод, параметры из формы и заголовки. Затем он отправляет запрос, используя GuzzleHttp\Client, чтобы получить ответ.


Подробнее здесь: https://stackoverflow.com/questions/716 ... guzzlehttp

Вернуться в «Php»