Reputation: 13
I'm building an API with Symfony 4 without API bundle. I'm creating all my endpoints manualy, everything is working fine. My problem is when I'm trying to upload multiple files. I have an entity with a field pictures where I need the user to upload multiple files. The problem is that I can't get files, I only receive ONE file.
Here is the field on my entity, the is an array type, I don't know if this is the best pratice :
/**
* @ORM\Column(type="array")
* @OA\Property(type="array")
* @Groups("main")
*/
private $pictures = [];
In my controller I'm trying to count files (only to test), but I always have 1 file :
$files = $request->files;
return $this->json(count($files)); // result 1
The curl used to get this result :
curl -H "Authorization: Bearer MY_TOKEN" -F "pictures=@PATH_TO_FILE\4b737fac533294776e386a3469e84e16.png" -F "pictures=@PATH_TO_FILE\azekh1454621e54516ze321a511z6259.png" http://127.0.0.1:8000/api/incidents/
add
I also tried with Postman, same result. This is my first API, I'm kinda lost ! I tried a LOT of thing, everything failed :(
Can anyone give me a clue to find the solution please ?
Thanks !!
Upvotes: 0
Views: 728
Reputation: 8374
like with any other request parameter provided, multiple instances of exactly the same parameter usually override each other:
https://example.org/?param=1¶m=2
will be turned into
['param' => 2] // in $_REQUEST or whatever
so, sending two files with pictures=...
will suffer the same fate.
to fix that problem, php does understand the []
syntax:
https://example.org/?param[]=1¶m[]=2
will be turned into
['param' => [1,2]]
so, for curl it's sufficient to turn pictures=...
into pictures[]=...
.
Files can be transfered in different ways. PHP has a few pitfalls, for example, that it will only accept files when sent as multipart/form-data
(source) which leads to the postman problem, which apparently by default sends files differently and you have to set it differently, see the following SO question for some hints:
Upload an image through HTTP POST with Postman
Upvotes: 1