我已设法使用以下步骤重命名批处理中的现有文件:
- 假设您的 config/filesystems.php 如下所示:
'disks' => [
's3_test_bucket' => [
'driver' => 's3',
'key' => env('AWS_KEY', 'your_aws_key_here'),
'secret' => env('AWS_SECRET','your_aws_secret_here'),
'region' => env('AWS_REGION', 'your_aws_region_here'),
'version' => 'latest',
'bucket' => 'my-test-bucket',
],
];
- 假设您的 AWS S3 上有 my-test-bucket。
-
假设您在 my-test-bucket/test-directory 目录中有以下文件。
即
- test-files-1.csv
- test-files-2.csv
- test-files-3.csv
调用以下函数以重命名 S3 存储桶上选定目录中的现有文件。
$directoryPath = 'test-directory';
$storage = new MyStorageRepository();
$storage->renameAnyExistingFilesOnImportDirectory('my-test-bucket', 'test-directory');
-
输出:my-test-bucket/test-directory 目录中的文件应重命名如下:
- test-files-1--1548870936.csv
- test-files-2--1548870936.csv
- test-files-3--1548870936.csv
在您的类中包含以下库类或方法,您应该会很好。
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Storage;
class MyStorageRepository
{
public function renameAnyExistingFilesOnImportDirectory($bucket, $directoryPath)
{
$directoryPath = App::environment() . '/' . $directoryPath;
$storage = Storage::disk('s3_test_bucket');
$suffix = '--' . time(); // File suffix to rename.
if ($storage->exists($directoryPath)) {
$this->renameStorageDirectoryFiles($directoryPath, $storage, $suffix);
}
}
private function getNewFilename($filename, $suffix = null)
{
$file = (object) pathinfo($filename);
if (!$suffix) {
$suffix = '--' . time();
}
return $file->dirname . '/' . $file->filename . $suffix . '.' . $file->extension;
}
private function renameStorageDirectoryFiles($directoryPath, $storage = null, $suffix = null, $filesystemDriver = null)
{
if (!$storage) {
$storage = Storage::disk($filesystemDriver);
}
// List all the existing files from the directory
$files = $storage->files($directoryPath);
if (count($files) < 1 ) return false;
foreach($files as $file) {
// Get new filename
$newFilename = Helpers::getNewFilename($file, $suffix);
// Renamed the files
$storage->move($file, $newFilename);
}
}
}