Amp\Artax\FormBody::addFile PHP Method

addFile() public method

Add a file field to the form entity body
public addFile ( string $name, string $filePath, string $contentType = 'application/octet-stream' ) : self
$name string
$filePath string
$contentType string
return self
    public function addFile($name, $filePath, $contentType = 'application/octet-stream')
    {
        $filePath = (string) $filePath;
        $fileName = basename($filePath);
        $this->fields[] = [(string) $name, new FileBody($filePath), $contentType, $fileName];
        $this->isMultipart = true;
        $this->cachedBody = $this->cachedLength = $this->cachedFields = null;
        return $this;
    }

Usage Example

 public function testMultipartBodyRequest()
 {
     $uri = 'http://httpbin.org/post';
     $client = new Client();
     $field1 = 'test val';
     $file1 = __DIR__ . '/fixture/lorem.txt';
     $file2 = __DIR__ . '/fixture/answer.txt';
     $boundary = 'AaB03x';
     $body = new FormBody($boundary);
     $body->addField('field1', $field1);
     $body->addFile('file1', $file1);
     $body->addFile('file2', $file2);
     $request = (new Request())->setBody($body)->setUri('http://httpbin.org/post')->setMethod('POST');
     $promise = $client->request($request);
     $response = \Amp\wait($promise);
     $this->assertEquals(200, $response->getStatus());
     $result = json_decode($response->getBody(), true);
     $this->assertEquals($field1, $result['form']['field1']);
     $this->assertEquals(file_get_contents($file1), $result['files']['file1']);
     $this->assertEquals(file_get_contents($file2), $result['files']['file2']);
     $this->assertEquals('multipart/form-data; boundary=' . $boundary, $result['headers']['Content-Type']);
 }