Skip to content

Commit 4d2a0e4

Browse files
committed
minor #18333 [HttpClient] Support file uploads by nesting resource streams in body option (javiereguiluz)
This PR was squashed before being merged into the 6.3 branch. Discussion ---------- [HttpClient] Support file uploads by nesting resource streams in body option Fixes #18232. I think that in the `versionadded` directive we should briefly mention the old way of doing things because it changes a lot from previous versions and this can confuse readers. Commits ------- 3f996ca [HttpClient] Support file uploads by nesting resource streams in body option
2 parents 1677413 + 3f996ca commit 4d2a0e4

File tree

1 file changed

+15
-14
lines changed

1 file changed

+15
-14
lines changed

http_client.rst

+15-14
Original file line numberDiff line numberDiff line change
@@ -607,22 +607,23 @@ A generator or any ``Traversable`` can also be used instead of a closure.
607607

608608
$decodedPayload = $response->toArray();
609609

610-
To submit a form with file uploads, it is your responsibility to encode the body
611-
according to the ``multipart/form-data`` content-type. The
612-
:doc:`Symfony Mime </components/mime>` component makes it a few lines of code::
610+
To submit a form with file uploads, pass the file handle to the ``body`` option::
613611

614-
use Symfony\Component\Mime\Part\DataPart;
615-
use Symfony\Component\Mime\Part\Multipart\FormDataPart;
612+
$fileHandle = fopen('/path/to/the/file' 'r');
613+
$client->request('POST', 'https://...', ['body' => ['the_file' => $fileHandle]]);
616614

617-
$formFields = [
618-
'regular_field' => 'some value',
619-
'file_field' => DataPart::fromPath('/path/to/uploaded/file'),
620-
];
621-
$formData = new FormDataPart($formFields);
622-
$client->request('POST', 'https://...', [
623-
'headers' => $formData->getPreparedHeaders()->toArray(),
624-
'body' => $formData->bodyToIterable(),
625-
]);
615+
By default, this code will populate the filename and content-type with the data
616+
of the opened file, but you can configure both with the PHP streaming configuration::
617+
618+
stream_context_set_option($fileHandle, 'http', 'filename', 'the-name.txt');
619+
stream_context_set_option($fileHandle, 'http', 'content_type', 'my/content-type');
620+
621+
.. versionadded:: 6.3
622+
623+
The feature to upload files using handles was introduced in Symfony 6.3.
624+
In previous Symfony versions you had to encode the body contents according
625+
to the ``multipart/form-data`` content-type using the :doc:`Symfony Mime </components/mime>`
626+
component.
626627

627628
.. tip::
628629

0 commit comments

Comments
 (0)