Malay M
Malay M

Reputation: 1759

How to upload a file using zend HttpClient?

I'm using HTTP client. How to attach a file while sending a post request?

Here's my code:

function executePost($postdata = [], $full_file_path = ''){
    self::$client = new Zend\Http\Client(null, 
            ['timeout' => 30] // updated to 30 sec
    );
    self::$client->setEncType(Zend\Http\Client::ENC_URLENCODED);

    self::$client->setUri($url);
    self::$client->setMethod($method);
    self::$client->setParameterPost($postdata);

    $response = $client->send();
    Debug::dump($response->getContent(),$label='Response',$echo=true);
}

I have tried $postdata['file_contents'] = '@'.$full_file_path; but it doesn't help.

Does anyone have an idea on how to attach file with the post data?

Thanks in advance.

Upvotes: 1

Views: 1868

Answers (1)

guessimtoolate
guessimtoolate

Reputation: 8642

Instead of using that data array try using the designated method called setFileUpload. So in your example it could look like so:

$client = new \Zend\Http\Client(null, ['timeout' => 30]);
$client->setUri($url);
$client->setFileUpload($full_file_path, 'file_contents');
$client->setMethod('POST'); // this must be either POST or PUT
$response = $client->send();

setFileUpload should also set the enc type.

There's a doc section related to that here.

Upvotes: 2

Related Questions