Skip to content

Commit ce96acb

Browse files
authored
fix(file-upload): always JSON encode field values (#2065)
1 parent df0365e commit ce96acb

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

core/file-upload.md

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,34 @@ The file and the resource fields will be posted to the resource endpoint.
330330

331331
This example will use a custom `multipart/form-data` decoder to deserialize the resource instead of a custom controller.
332332

333+
> [!WARNING]
334+
> Make sure to encode the fields in JSON before sending them.
335+
336+
For instance, you could do something like this:
337+
```js
338+
async function uploadBook(file) {
339+
const bookMetadata = {
340+
title: "API Platform Best Practices",
341+
genre: "Programming"
342+
};
343+
344+
const formData = new FormData();
345+
for (const [name, value] of Object.entries(bookMetadata)) {
346+
formData.append(name, JSON.stringify(value));
347+
}
348+
formData.append('file', file);
349+
350+
const response = await fetch('https://my-api.com/books', {
351+
method: 'POST',
352+
body: formData
353+
});
354+
355+
const result = await response.json();
356+
357+
return result;
358+
}
359+
```
360+
333361
### Configuring the Existing Resource Receiving the Uploaded File
334362

335363
The `Book` resource needs to be modified like this:
@@ -416,9 +444,7 @@ final class MultipartDecoder implements DecoderInterface
416444

417445
return array_map(static function (string $element) {
418446
// Multipart form values will be encoded in JSON.
419-
$decoded = json_decode($element, true);
420-
421-
return \is_array($decoded) ? $decoded : $element;
447+
return json_decode($element, true, flags: \JSON_THROW_ON_ERROR);
422448
}, $request->request->all()) + $request->files->all();
423449
}
424450

0 commit comments

Comments
 (0)