I am building an API using the FOSRestBundle and am at the stage where I need to implement the handling of the creation of new entities that contain binary data.
Following the methods outlined on Sending binary data along with a REST API request
sending the data as multipart/form-data
feels the most practical for our implementation due to the ~33% added bandwidth required for Base64.
Question
How can I configure the REST end point to both handle the file within the request and perform validation on the JSON encoded entity when sending the data as multipart/form-data
?
When just sending the raw JSON I have been using Symfony's form handleRequest
method to perform validation against the custom FormType
. For example:
$form = $this->createForm(new CommentType(), $comment, ['method' => 'POST']);
$form->handleRequest($request);
if ($form->isValid()) {
// Is valid
}
The reason I like this approach is so that I can have more control over the population of the entity depending whether the action is an update (PUT) or new (POST).
I understand that Symfony's Request
object handles the request such that previously the JSON data would be the content
variable but is now keyed under request->parameters->[form key]
and the files within the file bag (request->files
).
Here is more clear solution: http://labs.qandidate.com/blog/2014/08/13/handling-angularjs-post-requests-in-symfony/
It seems that there is no clean way to retrieve the Content-Type of the form-data without parsing the raw request.
If your API does support only json input or if you can add a custom header (see comments below), you can use this solution :
First you must implements your own
body_listener
:Then in your config file :
Finally, you'll just have to call
handleRequest
in your controller. Ex:Using this request format (
form
must be replace by your form name):Modify the app to send the file content in the JSON.
JSON
with all your field (included the one with the file content)JSON
to the server.You get the file content in a base64 encoded string. You can then decode it and validate it.
Your
JSON
will look like:After giving up and looking at an alternative option of having a separate endpoint for the image upload. For example:
POST /comments
POST /comments/{id}/image
I found there is already a bundle which provides various RESTful uploading processes. One of which was the one I originally wanted of being able to parse
multipart/form-data
into an entity whilst extracting the file.