Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get image from resources in Laravel?

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 
like image 774
Dev Avatar asked Aug 03 '16 07:08

Dev


2 Answers

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.

like image 59
Alfonz Avatar answered Oct 08 '22 05:10

Alfonz


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') }}" />
like image 27
Ronald Avatar answered Oct 08 '22 06:10

Ronald