0

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 !!

Lambert
  • 13
  • 4
  • 1
    php is designed that if your request has multiple assignments x='something' and x='else' it will be x='else' in the end and not x=['something', 'else']. the same applies to files. that's part 1 (the answer is, it must be `pictures[]=...`, possibly escaped, I don't remember ...) if that still doesn't help, have a look at https://www.php.net/manual/en/features.file-upload.php and read carefully. – Jakumi Sep 25 '19 at 13:55
  • Well, thanks for this response, this is working if I add [] to my curl, but I don't know why this is not working in Postman. I though Postman can handle this kind of things :D – Lambert Sep 25 '19 at 14:29

1 Answers1

1

like with any other request parameter provided, multiple instances of exactly the same parameter usually override each other:

https://example.org/?param=1&param=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&param[]=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

Jakumi
  • 8,043
  • 2
  • 15
  • 32
  • Alright, that's working now, I added bracket to my curl to turn it into array :) Thank for your help !! – Lambert Sep 26 '19 at 08:14