Laravel Retrieve Images from storage to view - laravel

I am using below code to store the uploaded file
$file = $request->file($file_attachment);
$rules = [];
$rules[$file_attachment] = 'required|mimes:jpeg|max:500';
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return redirect()->back()
->with('uploadErrors', $validator->errors());
}
$userid = session()->get('user')->id;
$destinationPath = config('app.filesDestinationPath') . '/' . $userid . '/';
$uploaded = Storage::put($destinationPath . $file_attachment . '.' . $file->getClientOriginalExtension(), file_get_contents($file->getRealPath()));
The uploaded files are stored in storage/app/2/filename.jpg
I want to show back the user the file he uploaded. How can i do that?
$storage = Storage::get('/2/filename.jpg');
I am getting unreadable texts. I can confirm that the file is read. But how to show it as an image to the user.
Hope i made my point clear.
Working Solution
display.blade.php
<img src="{{ URL::asset('storage/photo.jpg') }}" />
web.php
Route::group(['middleware' => ['web']], function () {
Route::get('storage/{filename}', function ($filename) {
$userid = session()->get('user')->id;
return Storage::get($userid . '/' . $filename);
});
});
Thanks to: #Boghani Chirag and #rkj

File not publicly accessible like you said then read file like this
$userid = session()->get('user')->id;
$contents = Storage::get($userid.'/file.jpg');
Assuming your file is at path storage/app/{$userid}/file.jpg
and default disk is local check config/filesystems.php
File publicly accessible
If you want to make your file publicly accessible then store file inside this storage/app/public folder. You can create subfolders inside it and upload there. Once you store file inside storage/app/public then you have to just create a symbolic link and laravel has artisan command for it.
php artisan storage:link
This create a symbolic link of storage/app/public to public/storage. Means now you can access your file like this
$contents = Storage::disk('public')->get('file.jpg');
here the file physical path is at storage/app/public/file.jpg and it access through symbolic link path public/storage/file.jpg
Suppose you have subfolder storage/app/public/uploads where you store your uploaded files then you can access it like this
$contents = Storage::disk('public')->get('uploads/file.jpg');
When you make your upload in public folder then you can access it in view
echo asset('storage/file.jpg'); //without subfolder uploads
echo asset('storage/uploads/file.jpg');
check for details https://laravel.com/docs/5.6/filesystem#configuration

Remember put your folder in storage/app/public/
Create the symbolic linksymbolic link to access this folder
php artisan storage:link
if you want to access profile images of 2 folder then do like this in your blade file
<img src="{{ asset('storage/2/images/'.$user->profile_image) }}" />

Laravel 8
Controller
class MediaController extends Controller
{
public function show(Request $request, $filename)
{
$folder_name = 'upload';
$filename = 'example_img.jpeg';
$path = $folder_name.'/'.$filename;
if(!Storage::exists($path)){
abort(404);
}
return Storage::response($path);
}
}
Route
Route::get('media/{filename}', [\App\Http\Controllers\MediaController::class, 'show']);

Can you please try this code
routes.php
Route::group(['middleware' => ['web']], function() {
Route::get('storage/storage_inner_folder_fullpath/{filename}', function ($filename) {
return Image::make(storage_path() . '/storage_inner_folder_fullpath/' . $filename)->response();
});
});
view file code
<img src="{{ URL::asset('storage/storage_inner_folder_fullpath/'.$filename) }}" />
Thanks

Try this:
Storage::disk('your_disk_name')->getDriver()->getAdapter()->applyPathPrefix('your_file_name');
Good Luck !

Uploaded like this
$uploadedFile = $request->file('photo');
$photo = "my-prefix" . "_" . time() . "." . $uploadedFile->getClientOriginalExtension();
$photoPath = \Illuminate\Support\Facades\Storage::disk('local')->putFileAs(
"public/avatar",
$uploadedFile,
$photo
);
and then access like this
<img src="{{ asset('storage/avatar/'.$filename) }}" />

Create Route:
Route::get('image/{filename}', 'HomeController#displayImage')->name('image.displayImage');
Create Controller Method:
public function displayImage($filename)
{
$path = storage_public('images/' . $filename);
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
}
<img src="{{ route('image.displayImage',$article->image_name) }}" alt="" title="">

can You please try this
$storage = Storage::get(['type_column_name']);

Related

How can i upload image outside project folder Php Laravel?

I want to save uploaded file to '/home/user/images' folder.
Is there any way to do this?
My 1st try:
controller
public function save(Request $request) {
$file = $request->file('image');
$file_name = $file->getClientOriginalName();
$file_path = '/home/user/images';
$file->move($file_path, $file_name);
}
/////////////////////
My 2nd try:
filesystems.php
'disks' => [
..
'custom_folder' => [
'driver' => 'local',
'root' => '/home/user/images',
],
...
controller
public function save(Request $request) {
$file = $request->file('image');,
$file_name = $file->getClientOriginalName();
Storage::disk('custom_folder')->put($file_name, $file);
}
I'm sorry if there is anything I did wrong. I just started learning php and Laravel.
For now, I save the files in the 'public / images' file path. I will use these files in multiple projects in the future. So I thought of such a method but could not reach the result.
if($request->hasFile('image')){
$image = $request->image;
$image_new_name = $image->getClientOriginalName();
$image->move('storage/custom_folder/', $image_new_name);
}
"storage" folder can be found inside "public" folder; public/storage/custom_folder.
If you want it outside your server dir then create a symlink inside your project folder.

Referencing images using Laravel framework

I'm trying to referencing an image I Laravel but I don't know how to adding
<img src="{{ asset('images/avatar/helmet/'.Auth::user()->avatar()->first()->helmet.'.png')}}">
Did you save the file name with its original extension in the data base? If so, the code below should work.
<img src="{{ asset('images/avatar/helmet/'.Auth::user()->avatar)}}">
I will recommend to save the file with its original extension by adding ->getClientOriginalExtension().
It will look like this:
$image = $request->file('imagename');
if (isset($image))
{
$imagename = uniqid() .'-'. $image->getClientOriginalExtension();
if (!file_exists('Uploads/Media/Slider'))
{
mkdir('Uploads/Media/Slider', 0777 , true);
}
$image->move('Uploads/Media/Slider',$imagename);
}else {
$imagename = 'slider.png';
}

How to retrieve an image from the storage folder using image intervention in Laravel 5.2?

This solution works in the Public Folder most when switching to Storage folder I can not get the image and display in the view can anyone help me?
Controller
public function profile(){
return view('profile', array('user' => Auth::user()) );
}
public function update_avatar(Request $request){
// Handle the user upload of avatar
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save( storage_path('/uploads/avatars/' . $filename ) );
$user = Auth::user();
$user->avatar = $filename;
$user->save();
}
return view('profile', array('user' => Auth::user()) );
}
Route
Route::get('profile',
'UserController#profile');
Route::post('profile',
'UserController#update_avatar');
View
This was the call I made to return the image when it was in the public folder now that this in the Storage folder does not work, does anyone know how I can get the image from the storage folder and display it in the view?
<img src="/uploads/avatars/{{ Auth::user()->avatar }}">
Repository GitLab
https://gitlab.com/ronnyere/Laravel.git
Use Laravel filesystem to retrieve image from storage
https://laravel.com/docs/master/filesystem#retrieving-files

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
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.
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') }}" />
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 =)
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';
First, change your config/filesystems.php
'links' => [
public_path('storage') => storage_path('app/public'),
public_path('resources') => resource_path('images'),
],
Then normally run
asset('resources/image.png')
you will get the file URL.

How show images in laravel

I want to show all images that are in a particular folder, I have the folder path but I do not see how the number of images there are inside and how show all. Someone could help me?
If your files are inside public or a subfolder of it, this is is a way:
foreach (File::allFiles(public_path().'/assets/img/') as $file)
{
$filename = $file->getRelativePathName();
echo HTML::image('public/assets/img/'.$filename, $filename);
}
This is a router you can use to test it:
Route::any('images', function() {
$images = '';
foreach (File::allFiles(public_path() . '/assets/img/') as $file)
{
$filename = $file->getRelativePathName();
$images .= HTML::image('public/assets/img/'.$filename, $filename);
}
return "<htm><body>$images</body></htm>";
});
Edit the /assets/img/ to your own and just hit http://yourserver.dev/images.

Resources