|
| 1 | +Multi-part content |
| 2 | +================== |
| 3 | + |
| 4 | +HTTP message content may consist of several parts with different content type. This is usually necessary |
| 5 | +in case of a file upload request. You may compose a multi-part content using `addContent()`, `addFile()` or |
| 6 | +`addFileContent()` methods of [[\yii\httpclient\Request]]. |
| 7 | +For example, if you wish to emulate file uploading via web form, you can use code like following: |
| 8 | + |
| 9 | +```php |
| 10 | +use yii\httpclient\Client; |
| 11 | + |
| 12 | +$client = new Client(); |
| 13 | +$response = $client->createRequest() |
| 14 | + ->setMethod('post') |
| 15 | + ->setUrl('http://domain.com/file/upload') |
| 16 | + ->addFile('file', '/path/to/source/file.jpg') |
| 17 | + ->send(); |
| 18 | +``` |
| 19 | + |
| 20 | +If there is [[\yii\httpclient\Request::data]] specified, its values will be sent automatically as content parts |
| 21 | +in case request is marked as multi-part one. |
| 22 | +For example: assume we wish emulate submitting of the following form: |
| 23 | + |
| 24 | +```html |
| 25 | +<form name="profile-form" method="post" action="http://domain.com/user/profile" enctype="multipart/form-data"> |
| 26 | + <input type="text" name="username" value=""> |
| 27 | + <input type="text" name="email" value=""> |
| 28 | + <input type="file" name="avatar"> |
| 29 | + <!-- ... --> |
| 30 | +</form> |
| 31 | +``` |
| 32 | + |
| 33 | +you can do this using following code: |
| 34 | + |
| 35 | +```php |
| 36 | +use yii\httpclient\Client; |
| 37 | + |
| 38 | +$client = new Client(); |
| 39 | +$response = $client->createRequest() |
| 40 | + ->setMethod('post') |
| 41 | + ->setUrl('http://domain.com/user/profile') |
| 42 | + ->setData([ |
| 43 | + 'username' => 'johndoe', |
| 44 | + 'email' => 'johndoe@domain.com', |
| 45 | + ]) |
| 46 | + ->addFile('avatar', '/path/to/source/image.jpg') |
| 47 | + ->send(); |
| 48 | +``` |
0 commit comments