|
| 1 | +--- |
| 2 | +title: 'Multipart Bodies' |
| 3 | +prev_title: 'URL-Encoding Bodies' |
| 4 | +prev_link: '/docs/urlencoded' |
| 5 | +next_title: 'Notes' |
| 6 | +next_link: '/docs/notes' |
| 7 | +--- |
| 8 | + |
| 9 | +## Posting data as `multipart/form-data` |
| 10 | + |
| 11 | +### Using FormData API |
| 12 | + |
| 13 | +#### Browser |
| 14 | + |
| 15 | +```js |
| 16 | +const form = new FormData(); |
| 17 | +form.append('my_field', 'my value'); |
| 18 | +form.append('my_buffer', new Blob([1,2,3])); |
| 19 | +form.append('my_file', fileInput.files[0]); |
| 20 | + |
| 21 | +axios.post('https://example.com', form) |
| 22 | +``` |
| 23 | + |
| 24 | +The same result can be achieved using the internal Axios serializer and corresponding shorthand method: |
| 25 | + |
| 26 | +```js |
| 27 | +axios.postForm('https://httpbin.org/post', { |
| 28 | + my_field: 'my value', |
| 29 | + my_buffer: new Blob([1,2,3]), |
| 30 | + my_file: fileInput.files // FileList will be unwrapped as sepate fields |
| 31 | +}); |
| 32 | +``` |
| 33 | + |
| 34 | +HTML form can be passes directly as a request payload |
| 35 | + |
| 36 | +#### Node.js |
| 37 | + |
| 38 | +```js |
| 39 | +import axios from 'axios'; |
| 40 | + |
| 41 | +const form = new FormData(); |
| 42 | +form.append('my_field', 'my value'); |
| 43 | +form.append('my_buffer', new Blob(['some content'])); |
| 44 | + |
| 45 | +axios.post('https://example.com', form) |
| 46 | +``` |
| 47 | + |
| 48 | +Since node.js does not currently support creating a `Blob` from a file, you can use a third-party package for this purpose. |
| 49 | + |
| 50 | +```js |
| 51 | +import {fileFromPath} from 'formdata-node/file-from-path' |
| 52 | + |
| 53 | +form.append('my_field', 'my value'); |
| 54 | +form.append('my_file', await fileFromPath('/foo/bar.jpg')); |
| 55 | + |
| 56 | +axios.post('https://example.com', form) |
| 57 | +``` |
| 58 | + |
| 59 | +For Axios older than `v1.3.0` you must import `form-data` package. |
| 60 | + |
| 61 | +```js |
| 62 | +const FormData = require('form-data'); |
| 63 | + |
| 64 | +const form = new FormData(); |
| 65 | +form.append('my_field', 'my value'); |
| 66 | +form.append('my_buffer', new Buffer(10)); |
| 67 | +form.append('my_file', fs.createReadStream('/foo/bar.jpg')); |
| 68 | + |
| 69 | +axios.post('https://example.com', form) |
| 70 | +``` |
| 71 | + |
| 72 | +### 🆕 Automatic serialization |
| 73 | + |
| 74 | +Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData |
| 75 | +object if the request Content-Type header is set to `multipart/form-data`. |
| 76 | + |
| 77 | +The following request will submit the data in a FormData format (Browser & Node.js): |
| 78 | + |
| 79 | +```js |
| 80 | +import axios from 'axios'; |
| 81 | + |
| 82 | +axios.post('https://httpbin.org/post', { |
| 83 | + user: { |
| 84 | + name: 'Dmitriy' |
| 85 | + }, |
| 86 | + file: fs.createReadStream('/foo/bar.jpg') |
| 87 | +}, { |
| 88 | + headers: { |
| 89 | + 'Content-Type': 'multipart/form-data' |
| 90 | + } |
| 91 | +}).then(({data})=> console.log(data)); |
| 92 | +``` |
| 93 | + |
| 94 | +Axios FormData serializer supports some special endings to perform the following operations: |
| 95 | + |
| 96 | +- `{}` - serialize the value with JSON.stringify |
| 97 | +- `[]` - unwrap the array-like object as separate fields with the same key |
| 98 | + |
| 99 | +> NOTE: |
| 100 | +> unwrap/expand operation will be used by default on arrays and FileList objects |
| 101 | +
|
| 102 | +FormData serializer supports additional options via `config.formSerializer: object` property to handle rare cases: |
| 103 | + |
| 104 | +- `visitor: Function` - user-defined visitor function that will be called recursively to serialize the data object |
| 105 | +to a `FormData` object by following custom rules. |
| 106 | + |
| 107 | +- `dots: boolean = false` - use dot notation instead of brackets to serialize arrays and objects; |
| 108 | + |
| 109 | +- `metaTokens: boolean = true` - add the special ending (e.g `user{}: '{"name": "John"}'`) in the FormData key. |
| 110 | +The back-end body-parser could potentially use this meta-information to automatically parse the value as JSON. |
| 111 | + |
| 112 | +- `indexes: null|false|true = false` - controls how indexes will be added to unwrapped keys of `flat` array-like objects |
| 113 | + |
| 114 | + - `null` - don't add brackets (`arr: 1`, `arr: 2`, `arr: 3`) |
| 115 | + - `false`(default) - add empty brackets (`arr[]: 1`, `arr[]: 2`, `arr[]: 3`) |
| 116 | + - `true` - add brackets with indexes (`arr[0]: 1`, `arr[1]: 2`, `arr[2]: 3`) |
| 117 | + |
| 118 | +Let's say we have an object like this one: |
| 119 | + |
| 120 | +```js |
| 121 | +const obj = { |
| 122 | + x: 1, |
| 123 | + arr: [1, 2, 3], |
| 124 | + arr2: [1, [2], 3], |
| 125 | + users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}], |
| 126 | + 'obj2{}': [{x:1}] |
| 127 | +}; |
| 128 | +``` |
| 129 | + |
| 130 | +The following steps will be executed by the Axios serializer internally: |
| 131 | + |
| 132 | +```js |
| 133 | +const formData= new FormData(); |
| 134 | +formData.append('x', '1'); |
| 135 | +formData.append('arr[]', '1'); |
| 136 | +formData.append('arr[]', '2'); |
| 137 | +formData.append('arr[]', '3'); |
| 138 | +formData.append('arr2[0]', '1'); |
| 139 | +formData.append('arr2[1][0]', '2'); |
| 140 | +formData.append('arr2[2]', '3'); |
| 141 | +formData.append('users[0][name]', 'Peter'); |
| 142 | +formData.append('users[0][surname]', 'Griffin'); |
| 143 | +formData.append('users[1][name]', 'Thomas'); |
| 144 | +formData.append('users[1][surname]', 'Anderson'); |
| 145 | +formData.append('obj2{}', '[{"x":1}]'); |
| 146 | +``` |
| 147 | + |
| 148 | +```js |
| 149 | +import axios from 'axios'; |
| 150 | + |
| 151 | +axios.post('https://httpbin.org/post', { |
| 152 | + 'myObj{}': {x: 1, s: "foo"}, |
| 153 | + 'files[]': document.querySelector('#fileInput').files |
| 154 | +}, { |
| 155 | + headers: { |
| 156 | + 'Content-Type': 'multipart/form-data' |
| 157 | + } |
| 158 | +}).then(({data})=> console.log(data)); |
| 159 | +``` |
| 160 | + |
| 161 | +Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm` |
| 162 | +which are just the corresponding http methods with the content-type header preset to `multipart/form-data`. |
| 163 | + |
| 164 | +`FileList` object can be passed directly: |
| 165 | + |
| 166 | +```js |
| 167 | +await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files) |
| 168 | +``` |
| 169 | + |
| 170 | +All files will be sent with the same field names: `files[]`; |
0 commit comments