Maksym Rybalkin
Maksym Rybalkin

Reputation: 545

What's the simplest way to get links from Amazon S3 using Java?

I need to delete images from S3 which are not presented in my database. First of all, I need to get all the links to files in a bucket. Now I'm trying this way:

final ListObjectsV2Request goodsReq = new ListObjectsV2Request()
                .withBucketName(s3Properties.getBucketName());
        final ListObjectsV2Result goodsResult = s3Client.listObjectsV2(goodsReq);

However, this has lots of useless information, and I don't know what a field of ListObjectsV2Result is connected with a link. Is there another way possible? If it isn't, can you describe a useful way?

Upvotes: 0

Views: 317

Answers (1)

smac2020
smac2020

Reputation: 10734

When you say "links", do you mean an URL? Assuming yes - you can use the AWS SDK Java API (version 2) to get an Object URL:

public static void getURL(S3Client s3, String bucketName, String keyName ) {

        try {

            GetUrlRequest request = GetUrlRequest.builder()
                    .bucket(bucketName)
                    .key(keyName)
                    .build();

            URL url = s3.utilities().getUrl(request);
            System.out.println("The URL for  "+keyName +" is "+url.toString());

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

Upvotes: 2

Related Questions