I've been experimenting using the new Flysystem integration with Laravel 5. I am storing 'localised' paths to the DB, and getting the Storage facade to complete the path. For example I store screenshots/1.jpg and using
Storage::disk('local')->get('screenshots/1.jpg')
or
Storage::disk('s3')->get('screenshots/1.jpg')
I can retrieve the same file on different disks.
get retrieves the file contents, but I am hoping to use it in my views like this:
<img src="{{ Storage::path('screenshots/1.jpg') }}" />
but path, or anything able to retrieve the full path is not available (as far as I can see). So how can I return the full path? Or, I'm wondering if this is by design? If so, why am I not supposed to be able to get the full path? Or, am I going about this completely the wrong way?
The Path to your Storage disk would be :
$storagePath = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix()
I don't know any shorter solutions to that...
You could share the $storagePath to your Views and then just call
$storagePath."/myImg.jpg";
This method exists since Laravel 5.4, you can get it by:
$path = Storage::disk('public')->path($filename);
Edit: Solution for L5.2+
There's a better and more straightforward solution.
Use Storage::url($filename) to get the full path/URL of a given file. Note that you need to set S3 as your storage filesystem in config/filesystems.php: 'default' => 's3'
Of course, you can also do Storage::disk('s3')->url($filename) in the same way.
As you can see in config/filesystems.php there's also a parameter 'cloud' => 's3' defined, that refers to the Cloud filesystem. In case you want to mantain the storage folder in the local server but retrieve/store some files in the cloud use Storage::cloud(), which also has the same filesystem methods, i.e. Storage::cloud()->url($filename).
The Laravel documentation doesn't mention this method, but if you want to know more about it you can check its source code here.
This is how I got it to work - switching between s3 and local directory paths with an environment variable, passing the path to all views.
In .env:
APP_FILESYSTEM=local or s3
S3_BUCKET=BucketID
In config/filesystems.php:
'default' => env('APP_FILESYSTEM'),
In app/Providers/AppServiceProvider:
public function boot()
{
view()->share('dynamic_storage', $this->storagePath());
}
protected function storagePath()
{
if (Storage::getDefaultDriver() == 's3') {
return Storage::getDriver()
->getAdapter()
->getClient()
->getObjectUrl(env('S3_BUCKET'), '');
}
return URL::to('/');
}
If you just want to display storage (disk) path use this:
Storage::disk('local')->url('screenshots/1.jpg'); // storage/screenshots/1.jpg
Storage::disk('local')->url(''): // storage
Also, if you are interested, I created a package (https://github.com/fsasvari/laravel-uploadify) just for Laravel so you can use all those fields on Eloquent model fields:
$car = Car::first();
$car->upload_cover_image->url();
$car->upload_cover_image->name();
$car->upload_cover_image->basename();
$car->upload_cover_image->extension();
$car->upload_cover_image->filesize();
If you need absolute URL of the file, use below code:
$file_path = \Storage::url($filename);
$url = asset($file_path);
// Output: http://example.com/storage/filename.jpg
First get file url/link then path, as below:
$url = Storage::disk('public')->url($filename);
$path = public_path($url);
Well, weeks ago I made a very similiar question (Get CDN url from uploaded file via Storage): I wanted the CDN url to show the image in my view (as you are requiring ).
However, after review the package API I confirmed that there is no way do this task. So, my solution was avoid using flysystem. In my case, I needed to play with RackSpace. So, finally decide to create my use package and make my own storage package using The PHP SDK for OpenStack.
By this way, you have full access for functions that you need like getPublicUrl() in order to get the public URL from a cdn container:
/** #var DataObject $file */
$file = \OpenCloud::container('cdn')->getObject('screenshots/1.jpg');
// $url: https://d224d291-8316ade.ssl.cf1.rackcdn.com/screenshots/1.jpg
$url = (string) $file->getPublicUrl(UrlType::SSL);
In conclusion, if need to take storage service to another level, then flysystem is not enough. For local purposes, you can try #nXu's solution
this work for me in 2020 at laravel 7
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(800,600);
$image_resize->save(Storage::disk('episodes')->path('') . $imgname);
so you can use it like this
echo Storage::disk('public')->path('');
Store method:
public function upload($img){
$filename = Carbon::now() . '-' . $img->getClientOriginalName();
return Storage::put($filename, File::get($img)) ? $filename : '';
}
Route:
Route::get('image/{filename}', [
'as' => 'product.image',
'uses' => 'ProductController#getImage',
]);
Controller:
public function getImage($filename)
{
$file = Storage::get($filename);
return new Response($file, 200);
}
View:
<img src="{{ route('product.image', ['filename' => $yourImageName]) }}" alt="your image"/>
Another solution I found is this:
Storage::disk('documents')->getDriver()->getConfig()->get('url')
Will return the url with the base path of the documents Storage
Take a look at this: How to use storage_path() to view an image in laravel 4 . The same applies to Laravel 5:
Storage is for the file system, and the most part of it is not accessible to the web server. The recommended solution is to store the images somewhere in the public folder (which is the document root), in the public/screenshots/ for example.
Then when you want to display them, use asset('screenshots/1.jpg').
In my case, i made separate method for local files, in this file:
src/Illuminate/Filesystem/FilesystemAdapter.php
/**
* Get the local path for the given filename.
* #param $path
* #return string
*/
public function localPath($path)
{
$adapter = $this->driver->getAdapter();
if ($adapter instanceof LocalAdapter) {
return $adapter->getPathPrefix().$path;
} else {
throw new RuntimeException('This driver does not support retrieving local path');
}
}
then, i create pull request to framework, but it still not merged into main core yet:
https://github.com/laravel/framework/pull/13605
May be someone merge this one))
$url = $filename->getMedia('media_name');
Related
I'm trying to create and store some HTML code from a textarea into a file
fopen method in PHP will create a file if that file doesn't exist already but it is not working in Laravel 5.7
Here is my demo code
$plugin_html_file_nm = "plugin_html".time().".html";
$html_plugin = fopen("/public/plugin_html_storage/".$plugin_html_file_nm,"w");
fwrite($html_plugin,$request->input('plugin_html'));
$plugin->plugin_html = $plugin_html_file_nm;
This error is given fopen(/public/plugin_html_storage/plugin_html1546535810.html): failed to open stream: No such file or directory
Can anyone help me?
Laravel provides a helper public_path()
The public_path function returns the fully qualified path to the
public directory. You may also use the public_path function to
generate a fully qualified path to a given file within the public
directory
Maybe you need to add the full path. So:
$html_plugin = fopen(public_path("plugin_html_storage/.$plugin_html_file_nm"),"w");
Also, make sure you have writing privilegies. As the PHP documentation states:
The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access.
Your laravel app by default is served from the public directory.
So in order to achieve what you're trying to do, replace
$html_plugin = fopen("/public/plugin_html_storage/".$plugin_html_file_nm,"w");
with:
$html_plugin = fopen("./plugin_html_storage/".$plugin_html_file_nm, "w");
Note: The plugin_html_storage directory should be created in the public directory so the operation doesn't fail.
You just need to add the relative path.
$html_plugin = fopen("../public/plugin_html_storage/".$plugin_html_file_nm,"w");
file_put_contents(public_path()."plugin_html".time().".html",
$request->input('plugin_html'));
In a function used in Image Storage, I realized I MAY have been over-complicating the code. I have two examples that both return the same results.
First Example:
public function image(Request $request, User $user)
{
$file = $request->file('image');
$path = "user_" . $user->id . "_images";
$filename = $path . "/test.jpg";
Storage::disk('public')->put($filename, File::get($file));
return back();
}
This example was tested in two scenarios. Once with NO directory inside public, and it returned by creating public/user_1_images/test.jpg ...
The second scenario, we already had public/user_1_images/ as an empty directory. Meaning it already exists. So instead, it just put the file inside of there without creating the folder.
Second Example:
public function image(Request $request, User $user)
{
$file = $request->file('image');
$path = "user_" . $user->id . "_images";
if (!Storage::disk('public')->exists($path))
{
Storage::makeDirectory($path, 0755, true, true);
}
$filename = $path . "/test.jpg";
Storage::disk('public')->put($filename, File::get($file));
return back();
}
In this example, we're checking to see if public/user_1_images/ exists, and if it does not, we're creating the folder, and then putting the image inside.
Would I need to do this, if I can just have it automatically check/create/not-create by titling the file "user_1_images/test.jpg"?
It all depends on the driver you use. All drivers must implement AdapterInterface interface and that's the only requirement they must meet.
I had a brief look at some of the popular drivers:
Local driver always calls ensureDirectory() before writing to a path, hence there is no need to create directory manually.
FTP driver always calls ensureDirectory() before writing to a path, hence there is no need to create directory manually.
S3 driver doesn't ensure a directory exist, but all necessary directories are created in S3 when it's asked to write to a path that contains directories. So again, no need to create directory manually.
So it seems that with most (if not all) drivers you can simply write to a path and not worry whether directory exists or not.
Is there a way to delete all files in specific directory. I'm trying to clear all my files in my created folder backgrounds in storage\app\backgrounds but in docs seems no method for delete all.
Storage::delete('backgrounds\*.jpg');
I don't think if this is the best way to solve this. But I solved mine calling
use Illuminate\Filesystem\Filesystem;
Then initiate new instance
$file = new Filesystem;
$file->cleanDirectory('storage/app/backgrounds');
for Laravel >= 5.8
use Illuminate\Support\Facades\Storage;
// Get all files in a directory
$files = Storage::allFiles($dir);
// Delete Files
Storage::delete($files);
Just use it.
File::cleanDirectory($direction);
You can use Filesystem method cleanDirectory
$success = Storage::cleanDirectory($directory);
Please see documentation for more information:
https://laravel.com/api/5.5/Illuminate/Filesystem/Filesystem.html#method_cleanDirectory
In Laravel 5.8 you can use:
Storage::deleteDirectory('backgrounds');
Remember to include:
use Illuminate\Support\Facades\Storage;
In Laravel 5.7 you can empty a directory using the Storage facade like so:
Storage::delete(Storage::files('backgrounds'));
$dirs = Storage::directories('backgrounds');
foreach ($dirs as $dir) {
Storage::deleteDirectory($dir);
}
The delete() method can receive an array of files to delete, while deleteDirectory() deletes one directory (and its contents) at a time.
I don't think it's a good idea to delete and then re-create the directory as that can lead to unwanted race conditions.
I'm handling this by deleting the whole directory as I don't need it. But if, for any case, you need the directory you should be good by just recreating it:
$d = '/myDirectory'
Storage::deleteDirectory($d);
Storage::makeDirectory($d);
//You can use Illuminate\Filesystem\Filesystem and it's method cleanDirectory('path_to_directory).
For Example:
$FolderToDelete = base_path('path_to_your_directory');
$fs = new \Illuminate\Filesystem\Filesystem;
$fs->cleanDirectory($FolderToDelete);
//For Delete All Files From Given Directory.
$succes = rmdir($FolderToDelete);
//For Delete Directory
//This Method Works for me
#Laravel
#FileManager
#CleanDirectory
I have created a new storage disk for the public uploads. I use it like this:
Storage::disk('uploads')->get(...);
But I am trying to figure out a way to get the path to the disk itself, I have spent some considerable time wondering between the framework files, but couldn't find what I am looking for. I want to use it in a scenario like so:
$icon = $request->file('icon')->store('icons', 'uploads');
Image::make(Storage::disk('uploads')->path($icon))->resize(...)->save();
So, how to get a storage disk's path ?
Update 2022
You can get the path from the config:
config('filesystems.disks.uploads.root')
Anyway, I keep the old answer, as it still works and is not wrong:
There is a function for this!
Storage::disk('uploads')->path('');
https://laravel.com/api/5.8/Illuminate/Filesystem/FilesystemAdapter.html#method_path
Looks like this has been there since 5.4! I never noticed...
After extra search I found that I can use the following:
$path = Storage::disk('uploads')->getAdapter()->getPathPrefix();
But still, isn't a "->path()" method is a given here or what!
We can also access the disk storage path from configuration helper directly:
config('filesystems.disks');
There are helper functions in the framework now that can get some of the commonly used paths in the app fairly easily.
https://laravel.com/docs/5.8/helpers
For example, if you wanted to access a file from the public folder you could do the below.
$image_file_path = public_path("images/my_image.jpg")
This will return you a local path for a file located in your app under the public/images folder.
Laravel Default Method
return Storage::disk('disk_name')->path('');
Get List of All Directories using disk name
Storage::disk('disk_name')->directories()
I've been experimenting using the new Flysystem integration with Laravel 5. I am storing 'localised' paths to the DB, and getting the Storage facade to complete the path. For example I store screenshots/1.jpg and using
Storage::disk('local')->get('screenshots/1.jpg')
or
Storage::disk('s3')->get('screenshots/1.jpg')
I can retrieve the same file on different disks.
get retrieves the file contents, but I am hoping to use it in my views like this:
<img src="{{ Storage::path('screenshots/1.jpg') }}" />
but path, or anything able to retrieve the full path is not available (as far as I can see). So how can I return the full path? Or, I'm wondering if this is by design? If so, why am I not supposed to be able to get the full path? Or, am I going about this completely the wrong way?
The Path to your Storage disk would be :
$storagePath = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix()
I don't know any shorter solutions to that...
You could share the $storagePath to your Views and then just call
$storagePath."/myImg.jpg";
This method exists since Laravel 5.4, you can get it by:
$path = Storage::disk('public')->path($filename);
Edit: Solution for L5.2+
There's a better and more straightforward solution.
Use Storage::url($filename) to get the full path/URL of a given file. Note that you need to set S3 as your storage filesystem in config/filesystems.php: 'default' => 's3'
Of course, you can also do Storage::disk('s3')->url($filename) in the same way.
As you can see in config/filesystems.php there's also a parameter 'cloud' => 's3' defined, that refers to the Cloud filesystem. In case you want to mantain the storage folder in the local server but retrieve/store some files in the cloud use Storage::cloud(), which also has the same filesystem methods, i.e. Storage::cloud()->url($filename).
The Laravel documentation doesn't mention this method, but if you want to know more about it you can check its source code here.
This is how I got it to work - switching between s3 and local directory paths with an environment variable, passing the path to all views.
In .env:
APP_FILESYSTEM=local or s3
S3_BUCKET=BucketID
In config/filesystems.php:
'default' => env('APP_FILESYSTEM'),
In app/Providers/AppServiceProvider:
public function boot()
{
view()->share('dynamic_storage', $this->storagePath());
}
protected function storagePath()
{
if (Storage::getDefaultDriver() == 's3') {
return Storage::getDriver()
->getAdapter()
->getClient()
->getObjectUrl(env('S3_BUCKET'), '');
}
return URL::to('/');
}
If you just want to display storage (disk) path use this:
Storage::disk('local')->url('screenshots/1.jpg'); // storage/screenshots/1.jpg
Storage::disk('local')->url(''): // storage
Also, if you are interested, I created a package (https://github.com/fsasvari/laravel-uploadify) just for Laravel so you can use all those fields on Eloquent model fields:
$car = Car::first();
$car->upload_cover_image->url();
$car->upload_cover_image->name();
$car->upload_cover_image->basename();
$car->upload_cover_image->extension();
$car->upload_cover_image->filesize();
If you need absolute URL of the file, use below code:
$file_path = \Storage::url($filename);
$url = asset($file_path);
// Output: http://example.com/storage/filename.jpg
First get file url/link then path, as below:
$url = Storage::disk('public')->url($filename);
$path = public_path($url);
Well, weeks ago I made a very similiar question (Get CDN url from uploaded file via Storage): I wanted the CDN url to show the image in my view (as you are requiring ).
However, after review the package API I confirmed that there is no way do this task. So, my solution was avoid using flysystem. In my case, I needed to play with RackSpace. So, finally decide to create my use package and make my own storage package using The PHP SDK for OpenStack.
By this way, you have full access for functions that you need like getPublicUrl() in order to get the public URL from a cdn container:
/** #var DataObject $file */
$file = \OpenCloud::container('cdn')->getObject('screenshots/1.jpg');
// $url: https://d224d291-8316ade.ssl.cf1.rackcdn.com/screenshots/1.jpg
$url = (string) $file->getPublicUrl(UrlType::SSL);
In conclusion, if need to take storage service to another level, then flysystem is not enough. For local purposes, you can try #nXu's solution
this work for me in 2020 at laravel 7
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(800,600);
$image_resize->save(Storage::disk('episodes')->path('') . $imgname);
so you can use it like this
echo Storage::disk('public')->path('');
Store method:
public function upload($img){
$filename = Carbon::now() . '-' . $img->getClientOriginalName();
return Storage::put($filename, File::get($img)) ? $filename : '';
}
Route:
Route::get('image/{filename}', [
'as' => 'product.image',
'uses' => 'ProductController#getImage',
]);
Controller:
public function getImage($filename)
{
$file = Storage::get($filename);
return new Response($file, 200);
}
View:
<img src="{{ route('product.image', ['filename' => $yourImageName]) }}" alt="your image"/>
Another solution I found is this:
Storage::disk('documents')->getDriver()->getConfig()->get('url')
Will return the url with the base path of the documents Storage
Take a look at this: How to use storage_path() to view an image in laravel 4 . The same applies to Laravel 5:
Storage is for the file system, and the most part of it is not accessible to the web server. The recommended solution is to store the images somewhere in the public folder (which is the document root), in the public/screenshots/ for example.
Then when you want to display them, use asset('screenshots/1.jpg').
In my case, i made separate method for local files, in this file:
src/Illuminate/Filesystem/FilesystemAdapter.php
/**
* Get the local path for the given filename.
* #param $path
* #return string
*/
public function localPath($path)
{
$adapter = $this->driver->getAdapter();
if ($adapter instanceof LocalAdapter) {
return $adapter->getPathPrefix().$path;
} else {
throw new RuntimeException('This driver does not support retrieving local path');
}
}
then, i create pull request to framework, but it still not merged into main core yet:
https://github.com/laravel/framework/pull/13605
May be someone merge this one))
$url = $filename->getMedia('media_name');