Symfony REST file upload over PUT method
Asked Answered
A

2

8

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?

Ashlar answered 24/6, 2014 at 11:19 Comment(4)
Do you use a specific REST bundle? Ok my bad I did not see the FOSRestBundle tag. I wrote this to upload an image, but it can be the same logic for a file.Antisemite
I did test it but in the $request->getContent() is more as the content of the file there is also some header information and then the uploaded image is corruptAshlar
I am also searching for a proper answer how to deal with this. I actually I am able to read the file with: var_dump(file_get_contents('php://input')) but I am not able to convert this into a proper Symfony\Component\HttpFoundation\File\File class. This is what I actually want to achieve. Any new ideas?Amabil
save the content into a tmpfile e.g. with tempnam and create a new File($path) Symfony File is based on SplFileInfoAshlar
S
4

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.

Seleneselenious answered 28/11, 2017 at 5:19 Comment(0)
A
2

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();
Ashlar answered 30/8, 2018 at 18:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.