Home > Mobile >  Search files with prefix on S3 in Laravel 9
Search files with prefix on S3 in Laravel 9

Time:08-02

I'm working on a project that save file on S3. But I've never worked with S3 before. I want to retrieve the files that match this pattern: {id}_{YYYYMMDD}.pdf

I could do this Storage::disk('s3')->files(); with Storage, but I think it's not the solution because there are thousand of files.

I search through topics and this is one of the things I've tried so far:

public static function searchS3ByPrefix($path, $prefix) {
        try {
            $storage = Storage::disk('s3');
            $client = $storage->getAdapter()->getClient();     // ** error on this line
            $command = $client->getCommand('ListObjects');
            $command['Bucket'] = $storage->getAdapter()->getBucket();
            $command['Prefix'] = $path . $prefix;
            $result = $client->execute($command);

            return array_column($result['Contents'], 'Key');
        } 
        catch (\Exception $e) {
            Log::error($e);
            return [];
        }
    }

The error message said that getClient() is undefined in League\Flysystem\AwsS3V3\AwsS3V3Adapter

Do you have a solution for this? Thank you very much

CodePudding user response:

On the line where I commented error, just modify it into this: $client = $storage->getClient();

Note: In my case, the result will be empty if the prefix has slash / at the very beginning, so make sure to remove it. For example: '/data/1_' will not work, change it to 'data/1_'

  • Related