简体   繁体   中英

Error uploading images using Slim framework

I am trying to create an API endpoint using Slim that allows people upload images. I am however having issues as I keep getting this error message,

"Argument 2 passed to moveUploadedFile() must be an instance of UploadedFile, instance of Slim\\Http\\UploadedFile given"

This is what I am doing:

$directory = __DIR__.'/uploads';

function moveUploadedFile($directory,  UploadedFile $uploadedFile)
{
    $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
    // see http://php.net/manual/en/function.random-bytes.php
    $basename = bin2hex(random_bytes(8));
    $filename = sprintf('%s.%0.8s', $basename, $extension);

    $uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);

    return $filename;
}

$files = $request->getUploadedFiles();
$uploadedFile = $files['photo'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
    $filename = moveUploadedFile($directory, $uploadedFile);                    
}

Please how I solve this?

The error tells you that PHP is looking for class UploadedFile in current namespace because you add typehint for it. Since there is no class named UploadedFile in your current namespace, hence the error.

Add use clause for example

use Slim\Http\UploadedFile;

...
function moveUploadedFile($directory,  UploadedFile $uploadedFile)
{
    ...
}

or typehint full class name

function moveUploadedFile($directory,  Slim\Http\UploadedFile $uploadedFile)
{
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM