Spring , image path does not include AWS domain
I'm new to Spring and i'm trying to serve images from Amazon S3,for now I'm able to upload images, but when I try to access them via an end-point I don't see the aws domain in the path , in Django I used to pass the reqeuest context in the serializer but I don't know how to do it in Spring.
The response look like this :enter image description here
I need the domain in the image Path
To access images in an Amazon S3 bucket from a Spring app, you can use the AWS SDK for Java V2. For example, assume you want to read the image and return it as a byte array to pass to another AWS Service or download it in the browser.
Using the S3Client object's getObjectAsBytes method, you can get the image using the bucket name and key as the input.
public byte[] getObjectBytes (String bucketName, String keyName) {
s3 = getClient();
try {
GetObjectRequest objectRequest = GetObjectRequest
.builder()
.key(keyName)
.bucket(bucketName)
.build();
ResponseBytes<GetObjectResponse> objectBytes = s3.getObjectAsBytes(objectRequest);
byte[] data = objectBytes.asByteArray();
return data;
} catch (S3Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return null;
}
If on the other hand, you want to get a URL of an object in an Amazon S3 bucket, you can get this information as well using the the S3Client object's s3.utilities().getUrl method.
Example:
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);
}
}
This returns a value like:
https://bucketxxxxx.s3.amazonaws.com/people.png
To see the object using an URL like this - ensure that you have set the object to be read by public - otherwise the URL does not display the image. More infor here:
https://aws.amazon.com/premiumsupport/knowledge-center/read-access-objects-s3-bucket/
If you do not know how to code using the AWS SDK for Java V2, start here:
Get started with the AWS SDK for Java 2.x