Wrong path when downloading in Backpack CRUD view - laravel

i added an upload field in my CRUD Controller.
Upload works fine and file gets loaded in my /storage/private directory.
Here is filesystems.php file:
'private' => [
'driver' => 'local',
'root' => storage_path('private')
],
Here are my custom functions in the File.php Model:
public static function boot()
{
parent::boot();
static::deleting(function($file) {
\Storage::disk('private')->delete($file->file);
});
}
public function setFileAttribute($value)
{
$attribute_name = "file";
$disk = "private";
$destination_path = "";
// Cifratura del file
file_put_contents($value->getRealPath(), file_get_contents($value->getRealPath()));
$this->uploadFileToDisk($value, $attribute_name, $disk, $destination_path);
}
And here is my FileCRUDController.php code:
$this->crud->addField(
[ // Upload
'name' => 'file',
'label' => 'File to upload',
'type' => 'upload',
'upload' => true,
'disk' => 'private'
]);
When i try to download the file, however, it tries to fetch it from http://localhost:8000/storage/myfile.png instead of http://localhost:8000/storage/private/myfile.png
What i'm doing wrong? Thank you very much.
I would also like to know if there is a way to hook a custom function instead downloading the file directly from the CRUD view. My files are encrypted and i need a controller that cares about decrypting before sending the files to the user.

Method url() is still not usable for the files are placed in subdirectories.
You may also use the storage_path function to generate a fully qualified path to a given file relative to the storage directory:
$app_path = storage_path('app');
$file_path = storage_path('app/file.txt');
In reference to Issue #13610
The following works for version 5.3:
'my-disk' => [
'driver' => 'local',
'root' => storage_path(),
'url' => '/storage'
],
\Storage::disk('my-disk')->url('private/myfile.png')
this should return "/storage/private/myfile.png"

Related

how to delete mp3 file from folder using laravel

I am trying to delete the mp3 file from my local folder but unfortunately, it's not deleting please help me how to do that thanks?
controller
public function destroy(Request $request)
{
$hamdnaat = HamdoNaat::findOrFail($request->deleteId);
// apply your conditional check here
if (false) {
$response['error'] = 'This hamdnaat has something assigned to it.';
return response()->json($response, 409);
} else {
Storage::disk('audiofile')->delete($hamdnaat);
$response = $hamdnaat->delete();
// form helpers.php
logAction($request);
return response()->json($response, 200);
}
}
filesystem.php
'audiofile' => [
'driver' => 'local',
'root' => public_path('uploads/audio'),
'url' => env('APP_URL').'/uploads/audio',
'visibility' => 'public',
],
You need to give the file name to the delete function when you try deleting a file. So use
Storage::disk('audiofile')->delete($hamdnaat['name']);
If the name field doesn't include the extension, make sure you add it.
Storage::disk('audiofile')->delete($hamdnaat['name'] + '.mp3');

Laravel server, upload to public_html rather than upload in project folder

I've been trying surfing around this site looking for answers, but nothing works for me, i want to upload an image that save in public_html folder, instead of saving it in project folder (i seperate the project folder and put all public file in public_html folder). Already bind the public.path but it returns to my project folder, not public_html one.
My image upload controller
public static function uploadSubmit($request, $type, $for)
{
if($request->hasFile('photos'))
{
$allowedfileExtension=['jpg','png'];
$files = $request->file('photos');
foreach($files as $file)
{
$extension = $file->getClientOriginalExtension();
$check=in_array($extension,$allowedfileExtension);
//dd($check);
if($check)
{
$idx = Image::create([
'type' => $type,
'ids' => $for,
'ext' => $extension,
])->id;
$filename = $idx . '.' . $file->getClientOriginalExtension();
$filename = $file->storeAs(public_path('images/'), $filename);
}
}
}
}
i already do the public path bind like this in public_html/index.php
$app->bind('path.public', function() {
return __DIR__;
});
Thank you!
First, add config to filesystem.php on config folder:
'disks' => [
...
'public_html' => [
'driver' => 'local',
'root' => public_path(),
'visibility' => 'public',
],
...
],
Second, store image with code:
$file->storeAs('images', $filename, 'public_html')
P/S: Remember to configure the correct path for the public_html directory:
$app->bind('path.public', function(){
return __DIR__.'/../../public_html';
});
The public disk is intended for files that are going to be publicly accessible. By default, the public disk uses the local driver and stores these files in storage/app/public.
When using the local driver, all file operations are relative to the root directory defined in your filesystems configuration file. By default, this value is set to the storage/app directory. Therefore, the following method would store a file in storage/app/file.txt:
Storage::disk('local')->put('file.txt', 'Contents');
Or in your case in storage/app/images/file.txt
$file->storeAs(public_path('images/'), $filename);
You can change where these files are stored by changing the filesystems configuration file.
'local' => [
'driver' => 'local',
'root' => public_path(),
],

No such file, Storing file into the local storage is not working on production

I have a laravel application deployed on Elasticbeanstalk, I'm working on a feature where I need to get a zip file from s3 bucket, store it into the local storage in order to be able to use laravel-zip to remove a pdf file from that zip.
the code is working locally, but I'm receiving 'No Such file error' after testing on production:
// get the file from s3 and store it into local storage
$contents = Storage::disk('s3')->get($file_name);
$zip_local_name = 'my_file.zip';
Storage::disk('local')->put($zip_local_name, $contents);
// use laravel-zip to remove the unwanted pdf file from the result
$manager = new ZipManager();
$file_path = storage_path('app').'\\'.$zip_local_name; // register existing zips
$manager->addZip(Zip::open($file_path));
$zip = $manager->getZip(0);
$zip->delete($data["Iso_Bus"]["field_name"].'.pdf');
$zip->close();
I made sure that the file exists on s3, so I think my main problem is that the file is not stored in the local storage.
Any help is appreciated
Edit filesystems configrations:
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => '***',
'secret' => '***',
'region' => '***',
'bucket' => '****',
'url' => '****',
],
],
You're getting full path for the file wrongly, try this one instead:
$file_path = Storage::disk('local')->path($zip_local_name);
Note: It's better to check if the Storage::put was successful before continue:
// get the file from s3 and store it into local storage
$contents = Storage::disk('s3')->get($file_name);
$zip_local_name = 'my_file.zip';
if (Storage::disk('local')->put($zip_local_name, $contents)) {
// `Storage::put` returns `true` on success, `false` on failure.
// use laravel-zip to remove the unwanted pdf file from the result
$manager = new ZipManager();
$file_path = $file_path = Storage::disk('local')->path($zip_local_name);
$manager->addZip(Zip::open($file_path));
$zip = $manager->getZip(0);
$zip->delete($data["Iso_Bus"]["field_name"].'.pdf');
$zip->close();
}

Laravel-5 Deleting a folder or file does not work

<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use App\Good;
use App\Image;
class testpost extends Controller
{
//
public function execute(Request $request){
$file = "/Users/local/Desktop/111/2.png";
//$folder = "/Users/local/Desktop/111";
//unlink($file);
dd(Storage::delete($file));
//$status_delete_file=Storage::deleteDirectory($folder);
}
}
I'm trying delete file "/Users/local/Desktop/111/2.png". And Storage does not remove this file or folder 111. No errors, always returns "false". Tried to remove file through standard function PHP "unlink"
unlink($file)
All well removes!
Help me please.
Laravel 5.4
PHP 7.1.1
Laravel Storage Facade used for managing file in $root directory of your Laravel filesystem disk.
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
....
],
Please refer to this documentation. If your disk is local then $root directory will be storage/app, or if it public then $root directory will be storage/app/public. All operation: create, move, delete will do inside the defined $root directory.
By the way Laravel use league/flysystem package to handle Storage operation. You can see in the package source code what is Storage::delete() actualy doing.
// flysystem/src/Adapter/Local.php
/**
* #inheritdoc
*/
public function delete($path)
{
$location = $this->applyPathPrefix($path);
return unlink($location);
}
The delete function actually call unlink function. But adding directory prefix before do the operation.
So example: if a you want to delete file uploads/image.jpg in your public disk storage, you just need to call
Storage::delete('uploads/image.jpg')

Laravel download not working

In my application I have the need to:
upload a file
store information in the db
store the file in a local or remote filesystem
listing all the db rows with a link to download the file
remove the file from the db and from the filesystem
I am trying to develop the 4th but the solutions found here and here don't work for me.
My filesystem.php is:
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'visibility' => 'public',
],
'myftpsite' => [
'driver' => 'ftp',
'host' => 'myhost',
'username' => 'ftpuser,
'password' => 'ftppwd',
// Optional FTP Settings...
// 'port' => 21,
'root' => '/WRK/FILE/TEST',
// 'passive' => true,
// 'ssl' => true,
// 'timeout' => 30,
],
In the Controller I store the file with:
... validation here ...
$path = $request->uploadfile->storeAs('', $request->uploadfile->getClientOriginalName(), self::STORAGEDISK);
$file = new TESTFile;
... db code here ...
$file->save();
At this point I would like to retrive the variable to pass to the download methods (url or path of my file). I found 2 ways
Storage::url($pspfile->filename) *return* **/storage/** accept.png
Storage::disk(self::STORAGEDISK)->getDriver()->getAdapter()->applyPathPrefix($pspfile->filename) *return* C:\xampp\htdocs\myLaravel\ **storage** \app\accept.png
Any help or suggestion to do it in a better way will be very appreciated.
EDIT
For the moment I separete local/public from FTP.
The download is working if in the Controller I modify
$path = $request->uploadfile->storeAs('',
$request->uploadfile->getClientOriginalName()
,self::STORAGEDISK);
$file->fullpath = $path;
with
$file->fullpath = storage_path('app\\') . $path;
where 'app\' is the storage_path configured as root in filesystem.php
Moreover I can avoid to hardcode and use
$file->fullpath = Storage::disk(self::STORAGEDISK)
->getDriver()
->getAdapter()
->getPathPrefix() . $path;
In this way the download method can use
return response()->download($pspfile->fullpath);
I am still looking for a way to retrive a valid scr attribute for an img tag.
In addition I would like the same with remote stored files (maybe with local temp dir and file?)
I made something similar some time ago. Maybe this example code helps you.
class FileController extends Controller
{
// ... other functions ...
public function download(File $file)
{
if (Storage::disk('public')->exists($file->path)) {
return response()->download(public_path('storage/' . $file->path), $file->name);
} else {
return back();
}
}
public function upload()
{
$this->validate(request(), [
'file-upload' => 'required|file',
]);
$path = request()->file('file-upload')->store('uploads', 'public');
$file = new File;
$file->name = request()->file('file-upload')->getClientOriginalName();
$file->path = $path;
$file->save();
return back();
}
}

Resources