Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel FileNotFoundException thrown even though file exists

I ran into a problem today to which I can't seem to find a solution.

I'm creating a class for image upload. The upload itself works fine, but when I try to use the uploaded file for creating a thumbnail, for some reason the file can't be found.

My code:

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;
}

I know the file gets uploaded, but I have no idea why it can't be found. I've tried the same action using php artisan tinker and it works there, so the problem is not in the file path.

The only idea that I've come up so far is that is related to directory permissions, but I haven't been able to verify it yet.

like image 378
kajetons Avatar asked Jul 22 '14 09:07

kajetons


1 Answers

I believe your problem is here: $realPath = 'public/' . $filePath;. You need full path to your upload folder, so try replacing it with public_path()."/".$filePath.

like image 138
Eternal1 Avatar answered Sep 28 '22 23:09

Eternal1