Search code examples
symfonybehatminkguzzlegoutte

How to upload file with Guzzle client?


I'm trying to do BDD testing on an upload method. I'm using Behat with Mink in a symfony2 project.

Now I'm able to do simple request with this client:

$this->client = $this->mink->getSession('goutte')->getDriver()->getClient();

and

$this->client->request("POST", $url, array('content-type' => 'application/json'), array(), array(), $fields);

without any issue.

How to do a request with a file? I tried this:

$file = new \Symfony\Component\HttpFoundation\File\UploadedFile($path, "video");
$fields = json_encode($table->getColumnsHash()[0]);
$this->client->request("POST", $url, array('content-type' => 'multipart/form-data'), array($file), array(), $fields);

And the error I receive is:

PHP Fatal error: Call to undefined method GuzzleHttp\Stream\Stream::addFile()

What is the mistake? Thanks!


Solution

  • Ok finally I found the answer. Hope that helps someone.

    To upload a file, the correct way is:

    $fields = $table->getColumnsHash()[0]; //array('name' => 'test', 'surname' => 'test');
    $fields["file"] = fopen($path, 'rb');
    $this->client->request("POST", $url, array('Content-Type => multipart/form-data'), array(), array(), $fields);
    

    The trick is that you must not use the fourth parameter of the Goutte request, but you have to pass all fields as body raw data.