@@ -330,6 +330,34 @@ The file and the resource fields will be posted to the resource endpoint.
330
330
331
331
This example will use a custom ` multipart/form-data ` decoder to deserialize the resource instead of a custom controller.
332
332
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
+
333
361
### Configuring the Existing Resource Receiving the Uploaded File
334
362
335
363
The ` Book ` resource needs to be modified like this:
@@ -416,9 +444,7 @@ final class MultipartDecoder implements DecoderInterface
416
444
417
445
return array_map(static function (string $element) {
418
446
// 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);
422
448
}, $request->request->all()) + $request->files->all();
423
449
}
424
450
0 commit comments