'How Do I get Object URL for Amazon S3 object
I uploaded a file to my Amazon S3 bucket and I would like to get a url using the aws-SDK not console for the object that I put in. The object has public read access I have tried using
const url = s3Client.getSignedUrl('getObject', {
Bucket: srcBucket,
Key: key,
});
but that generates a signed url that expires. I can't seem to find any other method to fetch just the url. Any help is much appreciated.
Solution 1:[1]
You can get the URL of an Amazon S3 object using the AWS SDK for Java V2. Here is the code:
// snippet-start:[s3.java2.getobjecturl.import]
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetUrlRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import java.net.URL;
// snippet-end:[s3.java2.getobjecturl.import]
public class GetObjectUrl {
public static void main(String[] args) {
final String USAGE = "\n" +
"Usage:\n" +
" <bucketName> <keyName> \n\n" +
"Where:\n" +
" bucketName - the Amazon S3 bucket name.\n\n"+
" keyName - a key name that represents the object. \n\n";
if (args.length != 2) {
System.out.println(USAGE);
System.exit(1);
}
String bucketName = args[0];
String keyName = args[1];
Region region = Region.US_EAST_1 ;
S3Client s3 = S3Client.builder()
.region(region)
.build();
getURL(s3,bucketName,keyName);
s3.close();
}
// snippet-start:[s3.java2.getobjecturl.main]
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);
}
}
// snippet-end:[s3.java2.getobjecturl.main]
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | smac2020 |
