klein / klein.php

A fast & flexible router
MIT License
2.67k stars 289 forks source link

$request->files() is empty #373

Open bsdroot opened 7 years ago

bsdroot commented 7 years ago

Hi,

Tried to processs image upload using $request->files(), but it seem not working.

when i try

var_dump($request->files());

here is what i got

object(Klein\DataCollection\DataCollection)#44 (1) {
  ["attributes":protected]=>
  array(0) {
  }
}
ysguy commented 6 years ago

Did you ever figure this out?????

I have the same issue, i believe we need to handle the incoming files in the router page and not in the routed page and then build the request array and pass it along.

i.e. if index.php includes inc/router.php and router.php has the routing code

And the routing code takes the 'post' and routes it to a controller, then the router strips the incoming data. Which sucks and lacks examples completely.

The apparant way to handle this is something like:

**$klein->respond('POST', '/uploads/?', function($request, $response) use ($db, $errors){ $data = json_decode($request->body(), true);

**

I stole that code from an upload example here:

https://github.com/Mobnia/php-resumeable-upload

In this he does all the routing and processing within index.php which is not optimal for a scalable solution. I'd really like to know how to forward a POST request to a sub-php page and then handle the files from there. i.e.

** //API view (CATCHALL) foreach(array('upload', 'link', 'download') as $controller) { // Include all routes defined in a file under a given namespace $klein->with("/api/v1/$controller", "controllers/$controller.php");

} **

So if someone calls /api/v1/upload they get serviced by /controllers/upload.php

This works in terms of routing right now, but as you have able, the $request->files(); object is complete empty.

ngr900 commented 5 years ago

For any people who may have found this thread by googling for "php klein files empty" or something similar (like I did), I figured out my mistakes and hopefully this can help you as well.

First of all, when you call $request->files() it returns an instance of Klein's DataCollection object. When you var_dump this object, it's going to be "empty", that is all of its attributes will be protected.

That is the intended behavior, and it actually makes things easier. The uploaded files are wrapped in the DataCollection object which provides a plethora of methods to help you get the desired data out of it, such as count, exists, get, all, and so on (full documentation here).

To accomplish what the OP seems to have wanted, simply call $request->files()->all().