我今天遇到了一个似乎找不到解决办法的问题。
我正在创建一个图像上传类。上载本身工作正常,但当我尝试使用上载的文件创建缩略图时,由于某些原因找不到该文件。
我的代码:

private static $imageTypes = [
    "image/jpeg", "image/png", "image/gif", "image/x-ms-bmp"
];

public function upload(UploadedFile $file, $folder = 'common')
{
    if (!$this->isImage($file)) {
        return false;
    }

    $path = $this->createPath($file, $folder);

    try {
        $file->move($path, $file->getClientOriginalName());
        $filePath = sprintf("%s/%s", $path, $file->getClientOriginalName());
    } catch (FileException $e) {
        return false;
    }

    $realPath = 'public/' . $filePath;
    //dd(File::exists($realPath)); - this returns false
    //dd(File::get($realPath)); - this throws the exception
    $image = Image::make(File::get($realPath));

    // Code for creating a thumbnail - not implemented yet.
    $thumbnailPath = '';

    return [
        'image' => $path,
        'thumbnail' => $thumbnailPath
    ];
}

private function isImage(UploadedFile $file)
{
    $type = $file->getClientMimeType();

    return in_array($type, self::$imageTypes);
}

private function createPath(UploadedFile $file, $folder)
{
    $time = Carbon::now();

    $path = sprintf(
        'Code/images/uploads/%s/%d-%d',
        $folder,
        $time->year,
        $time->month
    );

    return $path;
}

我知道文件被上传了,但我不知道为什么找不到。我使用php artisan tinker尝试了相同的操作,它在那里工作,所以问题不在文件路径中。
到目前为止,我唯一想到的是,这与目录权限有关,但我还无法验证它。

最佳答案

我相信你的问题在这里:$realPath = 'public/' . $filePath;。您需要上传文件夹的完整路径,请尝试将其替换为public_path()."/".$filePath

07-27 19:26