Laravel文件存储:删除目录中的所有文件

35

有没有一种方法可以删除特定目录中的所有文件。我试图清理存储\app\backgrounds中我创建的文件夹背景中的所有文件,但在文档中似乎没有删除所有文件的方法。

Storage::delete('backgrounds\*.jpg');
8个回答

56

我不确定这是否是解决问题的最佳方法,但我通过打电话解决了我的问题。

use Illuminate\Filesystem\Filesystem;

然后初始化新实例

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

27

适用于 Laravel >= 5.8

    use Illuminate\Support\Facades\Storage;

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

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

1
它已经在Laravel 5.8中尝试过,并且运行良好。我在我的任务调度器中使用了它。 - Mycodingproject

22

只需使用它。

 File::cleanDirectory($direction);

这就是方法。 - user2094178
3
请注意,他正在使用门面“File”(use File; 或更好的 use Illuminate\Support\Facades\File;)。 您还可以与存储磁盘一起使用:File::cleanDirectory(Storage::disk('some-disk')->path('')); - Ken

6

6
谢谢提供cleanDirectory的提示,但它并不能解决调用那些Storage::cleanDirectory时出现错误的问题,错误信息为League\Flysystem\Filesystem::cleanDirectory - ßiansor Å. Ålmerol
3
这种方法在“Storage”门面上不存在静态方式。 - Soulriser
1
未定义的方法调用 League\Flysystem\Filesystem::cleanDirectory,laravel 6。 - xpredo

5
在 Laravel 5.8 中,您可以使用以下内容:
Storage::deleteDirectory('backgrounds');

请记住要包括以下内容:

use Illuminate\Support\Facades\Storage;

3
实际上,这也会删除目录本身。 - Mooncake

3
在 Laravel 5.7 中,您可以使用 Storage 外观清空一个目录,如下所示:
Storage::delete(Storage::files('backgrounds'));

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

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

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

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


1

我会通过删除整个目录来处理这个问题,因为我不需要它。但是,如果有任何情况下你需要该目录,你只需重新创建即可:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接