|
| 1 | +Multipart Stream Builder |
| 2 | +======================== |
| 3 | + |
| 4 | +A multipart stream is a special kind of stream that is used to transfer files over HTTP. There is currently no PSR-7 support for multipart streams as they are considered to be normal streams with a special content. A multipart stream HTTP request may look like this: |
| 5 | + |
| 6 | +.. code-block:: none |
| 7 | +
|
| 8 | + POST / HTTP/1.1 |
| 9 | + Host: example.com |
| 10 | + Content-Type: multipart/form-data; boundary=578de3b0e3c46 |
| 11 | +
|
| 12 | + --578de3b0e3c46 |
| 13 | + Content-Disposition: form-data; name="foo" |
| 14 | + Content-Length: 15 |
| 15 | +
|
| 16 | + A normal stream |
| 17 | + --578de3b0e3c46 |
| 18 | + Content-Disposition: form-data; name="bar"; filename="bar.png" |
| 19 | + Content-Length: 71 |
| 20 | + Content-Type: image/png |
| 21 | +
|
| 22 | + ?PNG |
| 23 | + |
| 24 | + ??? |
| 25 | + IHDR??? ??? ?????? ???? IDATxc???51?)?:??????IEND?B`? |
| 26 | + --578de3b0e3c46 |
| 27 | + Content-Type: text/plain |
| 28 | + Content-Disposition: form-data; name="baz" |
| 29 | + Content-Length: 6 |
| 30 | +
|
| 31 | + string |
| 32 | + --578de3b0e3c46-- |
| 33 | +
|
| 34 | +
|
| 35 | +In the request above you see a set of HTTP headers and a body with two streams. The body starts and ends with a "boundary" and it is also this boundary that separates the streams. That boundary also needs to be specified in the ``Content-Type`` header. |
| 36 | + |
| 37 | +Building a multipart stream |
| 38 | +``````````````````````````` |
| 39 | + |
| 40 | +To build a multipart stream you may use the ``MultipartStreamBuilder``. It is not coupled to any stream implementation so it needs a ``StreamFactory`` to create the streams. |
| 41 | + |
| 42 | +.. code-block:: php |
| 43 | +
|
| 44 | + $streamFactory = StreamFactoryDiscovery::find(); |
| 45 | + $builder = new MultipartStreamBuilder($streamFactory); |
| 46 | + $builder |
| 47 | + ->addResource('foo', $stream) |
| 48 | + ->addResource('bar', fopen($filePath, 'r'), ['filename' => 'bar.png']) |
| 49 | + ->addResource('baz', 'string', ['headers' => ['Content-Type' => 'text/plain']]); |
| 50 | +
|
| 51 | + $multipartStream = $builder->build(); |
| 52 | + $boundary = $builder->getBoundary(); |
| 53 | +
|
| 54 | + $request = MessageFactoryDiscovery::find()->createRequest( |
| 55 | + 'POST', |
| 56 | + 'http://example.com', |
| 57 | + ['Content-Type' => 'multipart/form-data; boundary='.$boundary], |
| 58 | + $multipartStream |
| 59 | + ); |
| 60 | +
|
| 61 | + $response = HttpClientDiscovery::find()->sendRequest($request); |
| 62 | +
|
| 63 | +The second parameter of ``MultipartStreamBuilder::addResource()`` is the content of the stream. The supported input is the same as ``StreamFactory::createStream()``. |
0 commit comments