I have a REST service where I want to update a file over PUT. When I use POST I used the following to get the uploaded file:
/**
* @var Request $request
*/
$request->files->get('file');
How to get an uploaded file send as PUT in Symfony Framework?
When you receive a POST request, you get a form submitted with one or more fields, and these fields include any files (possibly more than one file). The Content-Type
is multipart/form-data
.
When you PUT a file, the file's data is the request body. It's like the opposite of downloading a file with GET, where the file's content is the response body. In this case, if you receive a JPG file via a PUT request, the Content-Type
will be image/jpeg
. Of course this means you can only submit one file with each PUT request.
You should therefore use $request->getContent()
to receive the data. If the content has other information in addition to the submitted file, then technically speaking it is a malformed PUT request, and should probably be sent as a POST instead.
Although you can't send any other fields with a PUT request, you can still use the query string to provide some additional short fields where appropriate. For example you might upload a file via a PUT request to /api/record/123/attachment?filename=example.pdf
. This would allow you to receive both an uploaded file, another data field (the filename) and the ID (123) of the record to attach the upload to.
The easiest way where you don't need to change your api you submit the file and data you want to change as method POST
and add query parameter ?_method=PUT
to the url. In your front controller app.php
/index.php
you need to enable this feature with:
Request::enableHttpMethodParameterOverride();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With