简体   繁体   English

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

[英]Laravel File Storage delete all files in directory

Is there a way to delete all files in specific directory.有没有办法删除特定目录中的所有文件。 I'm trying to clear all my files in my created folder backgrounds in storage\\app\\backgrounds but in docs seems no method for delete all.我正在尝试清除我在 storage\\app\\backgrounds 中创建的文件夹背景中的所有文件,但在文档中似乎没有删除所有文件的方法。

Storage::delete('backgrounds\*.jpg');

I don't think if this is the best way to solve this.我不认为这是否是解决此问题的最佳方法。 But I solved mine calling但我解决了我的电话

use Illuminate\Filesystem\Filesystem;

Then initiate new instance然后启动新实例

$file = new Filesystem;
$file->cleanDirectory('storage/app/backgrounds');
    use Illuminate\Support\Facades\Storage;

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

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

就用它。

 File::cleanDirectory($direction);

You can use Filesystem method cleanDirectory您可以使用文件系统方法 cleanDirectory

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

Please see documentation for more information:请参阅文档了解更多信息:

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

In Laravel 5.8 you can use:Laravel 5.8 中,您可以使用:

Storage::deleteDirectory('backgrounds');

Remember to include:记得包括:

use Illuminate\Support\Facades\Storage;

In Laravel 5.7 you can empty a directory using the Storage facade like so:Laravel 5.7 中,您可以使用Storage门面清空目录,如下所示:

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

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

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

The delete() method can receive an array of files to delete, while deleteDirectory() deletes one directory (and its contents) at a time. delete()方法可以接收要删除的文件数组,而deleteDirectory()删除一个目录(及其内容)。

I don't think it's a good idea to delete and then re-create the directory as that can lead to unwanted race conditions.我认为删除然后重新创建目录不是一个好主意,因为这会导致不必要的竞争条件。

I'm handling this by deleting the whole directory as I don't need it.我通过删除整个目录来处理这个问题,因为我不需要它。 But if, for any case, you need the directory you should be good by just recreating it:但是,在任何情况下,如果您需要目录,只需重新创建它就可以了:

$d = '/myDirectory'
Storage::deleteDirectory($d);
Storage::makeDirectory($d);
//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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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