From f8f0b60a264345528e809b3b2df6cb73cfc769b2 Mon Sep 17 00:00:00 2001 From: Damian Date: Mon, 14 Jul 2025 09:54:02 +0200 Subject: [PATCH] fix(File upload): correct steps order Correct configuration steps order to allow to make a request `POST /media_objects`. Resolves: https://github.com/api-platform/api-platform/issues/2713 --- symfony/file-upload.md | 160 ++++++++++++++++++++--------------------- 1 file changed, 79 insertions(+), 81 deletions(-) diff --git a/symfony/file-upload.md b/symfony/file-upload.md index 5321853242b..100cbdd00a7 100644 --- a/symfony/file-upload.md +++ b/symfony/file-upload.md @@ -189,6 +189,85 @@ class MediaObjectNormalizer implements NormalizerInterface ``` +### Handling the Multipart Deserialization + +By default, Symfony is not able to decode `multipart/form-data`-encoded data. +We need to create our own decoder to do it: + +```php +requestStack->getCurrentRequest(); + + if (!$request) { + return null; + } + + return array_map(static function (string $element) { + // Multipart form values will be encoded in JSON. + return json_decode($element, true, flags: \JSON_THROW_ON_ERROR); + }, $request->request->all()) + $request->files->all(); + } + + public function supportsDecoding(string $format): bool + { + return self::FORMAT === $format; + } +} +``` + +If you're not using `autowiring` and `autoconfiguring`, don't forget to register the service and tag it as `serializer.encoder`. + +We also need to make sure the field containing the uploaded file is not denormalized: + +```php + true, + ]; + } +} +``` + +If you're not using `autowiring` and `autoconfiguring`, don't forget to register the service and tag it as `serializer.normalizer`. + ### Making a Request to the `/media_objects` Endpoint Your `/media_objects` endpoint is now ready to receive a `POST` request with a @@ -409,84 +488,3 @@ class Book // ... } ``` - -### Handling the Multipart Deserialization - -By default, Symfony is not able to decode `multipart/form-data`-encoded data. -We need to create our own decoder to do it: - -```php -requestStack->getCurrentRequest(); - - if (!$request) { - return null; - } - - return array_map(static function (string $element) { - // Multipart form values will be encoded in JSON. - return json_decode($element, true, flags: \JSON_THROW_ON_ERROR); - }, $request->request->all()) + $request->files->all(); - } - - public function supportsDecoding(string $format): bool - { - return self::FORMAT === $format; - } -} -``` - -If you're not using `autowiring` and `autoconfiguring`, don't forget to register the service and tag it as `serializer.encoder`. - -We also need to make sure the field containing the uploaded file is not denormalized: - -```php - true, - ]; - } -} -``` - -If you're not using `autowiring` and `autoconfiguring`, don't forget to register the service and tag it as `serializer.normalizer`. - -For resolving the file URL, you can use a custom normalizer, like shown in [the previous example](#resolving-the-file-url).