使用 php slim 3 检查文件是否已经上传到服务器

Check if the files have been uploaded to server with php slim 3

您好,在 slim 中有以下代码来保存文件

我想确保文件已上传到服务器,然后才 return 为真。或假

如何使用 Slim 或 PHP 做到这一点?

无故文件日志结果始终为空,正在上传文件

public function saveFiles(Array $files, $location) {
    try
    {
        /** @var UploadedFileInterface $file */
        foreach ($files as $file) {
            $fileLog = $file->moveTo($location . DIRECTORY_SEPARATOR . $file->getFilename());
        }

        return true;
    }
    catch(\Exception $e) {
        throw new Exception($e->getMessage());

根据此 PSR 的精简实现,如果在上传文件时出现问题,它总是会抛出异常。

我不知道你是否出于某种原因抛出另一个异常,但你可以像这样处理它:

public function saveFiles(Array $files, $location) {
    $result = true;

    foreach ($files as $file) {
        try {
            $fileLog = $file->moveTo($location . DIRECTORY_SEPARATOR . $file->getFilename());
        } catch(\Exception $e) {
            // Exception on file uploading happened, but 
            // we still continue loading other files
            $result = false;

            // Or just `return false;` if you don't want
            // to upload other files if exception happened
            // return false;
        }
    }

    return $result;
}

当然,可以扩展此方法以收集异常消息并return它们。