Access storage directory through JS Laravel

Viewed 1638

Is there is a way to access the storage directory, which is already linked to the public directory in JS?

I'm trying to make an upload image form. Validation script:

if ($request->hasFile('photos')) {
    $marker->photos = $request->photos->store('uploads');
}

It saves image in /storage/app/uploads/

I can't use this image, because website is in public folder, and can't have access to any other folders, so I did php artisan storage:link to create a sublink to storage folder.

Now, how can I access the image using 1) PHP 2) JS?

2 Answers

Yes, you have to use the public disk to store the file:

if ($request->hasFile('photos')) {
    $marker->photos = Storage::disk('public')->putFile('uploads', $request->file('photos'));
}

This syntax, similar to the one you are using, it's also possible to specify 'public' disk:

$marker->photos = $request->file('photos')->store(
    'uploads', 'public'
);

Then you'll can access to it by the url.

Laravel:

$url = asset('storage/uploads/filename.png');

$url = asset( Storage::url('uploads/filename.png') );

JS:

let imgSrc = "http://yourdomain/storage/uploads/filename.png";

References:

File Storage File Uploads.

File Storage The Public Disk.

File Storage File URLs.

From PHP, you would use something like this to access your storage/ directory:

if(file_exists('storage/app/uploads/photo.jpg')){
    $marker->photo = Storage::disk('local')->get('public/app/uploads/photo.jpg');
    // or to get the directory, which you can append ->response('png') to the end...
    $marker->photo = public_path('storage/app/uploads/photo.jpg');
}

To serve it from JS, you would do something similar, but have a Controller output the image when receiving an AJAX Request. Easiet method to achieve this without all this, if possible, would be through a blade template:

<img src = "{{asset('/storage/app/uploads/photo.jpg')}}">

which generates a link to the uploaded file by Laravel.

Related