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?

Alexander Schranz
  • 2,154
  • 2
  • 25
  • 42
  • Do you use a specific REST bundle? Ok my bad I did not see the FOSRestBundle tag. I wrote [this](http://stackoverflow.com/questions/17129874/uploading-image-file-through-api-using-symfony2-fosrestbundle/23825541#23825541) to upload an image, but it can be the same logic for a file. – AlixB Jun 24 '14 at 11:25
  • 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 corrupt – Alexander Schranz Jun 24 '14 at 12:07
  • 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? – bzin Jul 10 '15 at 13:43
  • save the content into a tmpfile e.g. with tempnam and create a new File($path) Symfony File is based on SplFileInfo – Alexander Schranz Aug 05 '15 at 07:32

2 Answers2

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.

Malvineous
  • 25,144
  • 16
  • 116
  • 151
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();
Alexander Schranz
  • 2,154
  • 2
  • 25
  • 42