Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(file-upload): always JSON encode field values #2065

Open
wants to merge 1 commit into
base: 4.0
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions core/file-upload.md
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,34 @@ The file and the resource fields will be posted to the resource endpoint.

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

> [!WARNING]
> Make sure to encode the fields in JSON before sending them.

For instance, you could do something like this:
```js
async function uploadBook(file) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will not working with swagger interface

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe, but the implementation is much simpler, isn't it?

const bookMetadata = {
title: "API Platform Best Practices",
genre: "Programming"
};

const formData = new FormData();
for (const [name, value] of Object.entries(bookMetadata)) {
formData.append(name, JSON.stringify(value));
}
formData.append('file', file);

const response = await fetch('https://my-api.com/books', {
method: 'POST',
body: formData
});

const result = await response.json();

return result;
}
```

### Configuring the Existing Resource Receiving the Uploaded File

The `Book` resource needs to be modified like this:
Expand Down Expand Up @@ -417,9 +445,7 @@ final class MultipartDecoder implements DecoderInterface

return array_map(static function (string $element) {
// Multipart form values will be encoded in JSON.
$decoded = json_decode($element, true);

return \is_array($decoded) ? $decoded : $element;
return json_decode($element, true, flags: \JSON_THROW_ON_ERROR);
}, $request->request->all()) + $request->files->all();
}

Expand Down