File uploads: How?

Hi,

I’m trying to upload a file using postman (following the docs) and I’m getting an error at this line:

$directory = $this->get('upload_directory');

I expect this relates to the container, in my settings file I have this:

//Upload directory
$settings['upload_directory'] = $settings['root'] . '/uploads';

How can I get the upload_directory into my __invoke method?

Also is UPLOAD_ERR_OK defined anywhere, doesn’t look like it. How/where should this be defined?

public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
{

    $supplier = (string)$args['supplier'];

    $responseData = ['supplier' => $supplier];

    $directory = $this->get('upload_directory');
    $uploadedFiles = $request->getUploadedFiles();

    // handle single input with single file upload
    $uploadedFile = $uploadedFiles['supplier'];
    if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
        $filename = $this->moveUploadedFile($directory, $uploadedFile);
        $responseData = [
            'filename' => $filename,
            'supplier' => $supplier,
            'message' => 'File uploaded'
        ];
        //$response->getBody()->write('Uploaded: ' . $filename . '<br/>');
    }

    // Invoke the Responder and pass in the response and responseData ($responseData)
    return $this->responder->withJson($response, $responseData);

}

The Slim documentation shows an example of retrieving the settings inside a route callback (closure).

If you want to retrieve the settings inside a class, you may better pass the settings via the constructor. Here you can find a tutorial: Slim 4 - Configuration.

The UPLOAD_ERR_OK constant is a native PHP constant. You don’t have to define it, it’s already defined. See here: Error Messages Explained

Awesome, thank you so much! I’ll take a look at that.

@odan Hey, got it working now, thank you so much! Never been so happy to see a JSON response!