20

I upload all user files to directory:

/resources/app/uploads/

I try to get image by full path:

http://localhost/resources/app/uploads/e00bdaa62492a320b78b203e2980169c.jpg

But I get error:

NotFoundHttpException in RouteCollection.php line 161:

How can I get image by this path?

Now I try to uplaod file in directory /public/uploads/ in the root:

$destinationPath = public_path(sprintf("\\uploads\\%s\\", str_random(8)));
$uploaded = Storage::put($destinationPath. $fileName, file_get_contents($file->getRealPath()));

It gives me error:

Impossible to create the root directory 
Dev
  • 935
  • 4
  • 14
  • 35

4 Answers4

34

You can make a route specifically for displaying images.

For example:

Route::get('/resources/app/uploads/{filename}', function($filename){
    $path = resource_path() . '/app/uploads/' . $filename;

    if(!File::exists($path)) {
        return response()->json(['message' => 'Image not found.'], 404);
    }

    $file = File::get($path);
    $type = File::mimeType($path);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);

    return $response;
});

So now you can go to localhost/resources/app/uploads/filename.png and it should display the image.

Alfonz
  • 905
  • 11
  • 24
  • 1
    Logic should not be placed in the path, it belongs in the controller or the model. – Sl4rtib4rtf4st Nov 23 '18 at 06:34
  • I tried this approach using Laravel 8 (ex: http://localhost:8000/files-layout-test/backend-layout-header-tb02-03.jpg) and I get ```Not Found``` message. But when I take away the file name extension (ex: http://localhost:8000/files-layout-test/backend-layout-header-tb02-03), goes through, but I need the file extension to be there. Any ideas on why this could be happening? – Jorge Mauricio May 22 '22 at 17:44
25

You may try this on your blade file. The images folder is located at the public folder

<img src="{{URL::asset('/images/image_name.png')}}" />

For later versions of Laravel (5.7 above):

<img src = "{{ asset('/images/image_name.png') }}" />
Ronald
  • 1,287
  • 3
  • 17
  • 27
10

Try {{asset('path/to/your/image.jpg')}} if you want to call it from your blade

or

$url = asset('path/to/your/image.jpg'); if you want it in your controller.

Hope it helps =)

Han Lim
  • 661
  • 7
  • 17
4

As @alfonz mentioned, resource_path() is correct way to get the resource folder directory. To get a specific file location, code will be like the following

 $path = resource_path() . '/folder1/folder2/filename.extension';
Hriju
  • 650
  • 1
  • 16
  • 26