我正在开发一个项目,需要从 storage/public/dir_name/
中删除所有文件。示例文件名为jIK4uh.png
。我应该使用 cron 作业来完成这项任务。这是我正在遵循的方法。
app/console/commands/ClearPublicStorage.png
class ClearPublicStorageCron extends Command {
protected $signature = 'storage:clear';
public function handle()
{
Log::info("Public storage files cleared!");
// tasks logic here
$this->info('Cron command run successfully');
}
}
app/Console/Kernel.php
class Kernel extends ConsoleKernel {
protected function schedule(Schedule $schedule)
{
$schedule->command('storage:clear')->hourly();
}
}
然后运行php artisan Schedule:run
现在如何按照此策略选择所有早于过去一小时的文件并每小时删除这些文件?或者有其他有效的想法来做这件事吗?
Laravel 版本:7.30
最佳答案
基本思想是使用存储lastModified
日期时间
从文件中获取最后修改的日期时间
$fileTime=Storage::disk('public')->lastModified('dummy.pdf');
$fileModifiedDateTime=Carbon::parse($fileTime);
if(Carbon::now()->gt($fileModifiedDateTime->addHour())){
//delete file here
}
如果您将文件名存储在数据库中,则可以根据文件上传日期删除
已更新
$files = Storage::disk("public")->allFiles("claim-images");
foreach ($files as $file) {
$time = Storage::disk('public')->lastModified($file);
$fileModifiedDateTime = Carbon::parse($time);
if (Carbon::now()->gt($fileModifiedDateTime->addHour(1))) {
Storage::disk("public")->delete($file);
}
//storage symbolic link files not required to delete.Still providing here for you reference
if (File::exists(public_path('storage/' . $file))) {
File::delete(public_path('storage/' . $file));
}
}
关于laravel - 如何删除超过一小时的公共(public)存储文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68001014/