Laravel File Storage删除目录中的所有文件

问题描述 投票:7回答:6

有没有办法删除特定目录中的所有文件。我正在尝试清除我在storage \ app \ backgrounds中创建的文件夹背景中的所有文件,但在docs中似乎没有删除所有方法。

Storage::delete('backgrounds\*.jpg');
php laravel laravel-5.5 file-storage
6个回答
17
投票

我不认为这是解决这个问题的最佳方法。但我解决了我的召唤

use Illuminate\Filesystem\Filesystem;

然后启动新实例

$file = new Filesystem;
$file->cleanDirectory('storage/app/backgrounds');

4
投票

您可以使用Filesystem方法cleanDirectory

$success = Storage::cleanDirectory($directory);

有关更多信息,请参阅文档:

https://laravel.com/api/5.5/Illuminate/Filesystem/Filesystem.html#method_cleanDirectory


2
投票

在Laravel 5.7中,您可以使用Storage外观清空目录,如下所示:

Storage::delete(Storage::files('backgrounds'));

$dirs = Storage::directories('backgrounds');

foreach ($dirs as $dir) {
    Storage::deleteDirectory($dir);
}

delete()方法可以接收要删除的文件数组,而deleteDirectory()一次删除一个目录(及其内容)。

我认为删除然后重新创建目录不是一个好主意,因为这会导致不必要的竞争条件。


1
投票
    use Illuminate\Support\Facades\Storage;

    // Get all files in a directory
    $files =   Storage::allFiles($dir);

    // Delete Files
    Storage::delete($files);

0
投票

我正在通过删除整个目录来处理这个,因为我不需要它。但是,无论如何,如果您需要该目录,只需重新创建它就应该是好的:

$d = '/myDirectory'
Storage::deleteDirectory($d);
Storage::makeDirectory($d);

0
投票

在Laravel 5.8中,您可以使用:

Storage::deleteDirectory('backgrounds');

请记住包括:

use Illuminate\Support\Facades\Storage;

0
投票
//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
© www.soinside.com 2019 - 2024. All rights reserved.