简体   繁体   中英

Get the right URL to storage path (Laravel)

I am trying to get the full url of a file I have hosted in the storage folder but I am unable to get it right. I work with Laravel 7.

The url I am trying to get is:

https://www.example.com/panel1/storage/app/folder/file.txt

I have tried many different ways but I never get the right address. For example:

$url = asset('storage/app/folder/file.txt');
https://www.example.com/panel1/public/storage/app/folder/file.txt

$url = storage_path('app/folder/file.txt');
https://www.example.com/var/www/panel1/storage/app/folder/file.txt

$url = Storage::disk('local')->path('folder');
https://www.example.com/var/www/panel1/storage/app/storage/app/folder/file.txt

$url = Storage::url('app/folder/file.txt');
https://www.example.com/storage/app/folder/file.txt

I have read about the option to create a symbolic link from the storage folder to the public folder, but I am worried about these files being accessible to any user as they are private and their content should only be accessible to the owner of the file.

Does anyone know what I am doing wrong and how to correct it?

Thanks in advance.

If the files are private then you can't create a URL to them for anyone directly. If you don't want public access to them then you will have to proxy them somehow:

Consider this sample code:

Route::get('privateFile/{filepath}', function ($filepath) {
    // Check if user can access file somehow
    return response->download(Storage::disk('local')->path('folder'));
})->where('filepath', '.*')->middleware('auth')->name('privateFileDownload');

Then to generate URLs to the file you'd do:

route('privateFileDownload', [ 'filepath' => 'app/folder/file.txt' ]);

This way you can control who can download which files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM