Send an HTTP HEAD request to the object. A HEAD request will retrieve the same HTTP headers as a GET request, but it will not retrieve the body of the object (saving you bandwidth). You can then parse out the Content-Length header value from the HTTP response headers.
You can also do a listing of the contents of the bucket. The metadata in the listing contains the file sizes of all of the objects. This is how it's implemented in the AWS SDK for PHP.
Very important to execute the code in AsyncTask or any means to get you in a background thread, otherwise you get an exception for running network on ui thread.
I do something like this in Python to get the cumulative size of all files under a given prefix:
import boto3
bucket = 'your-bucket-name'
prefix = 'some/s3/prefix/'
s3 = boto3.client('s3')
size = 0
result = s3.list_objects_v2(Bucket=bucket, Prefix=prefix)
size += sum([x['Size'] for x in result['Contents']])
while result['IsTruncated']:
result = s3.list_objects_v2(
Bucket=bucket, Prefix=prefix,
ContinuationToken=result['NextContinuationToken'])
size += sum([x['Size'] for x in result['Contents']])
print('Total size in MB: ' + str(size / (1000**2)))
This is a solution for whoever is using Java and the S3 java library provided by Amazon. If you are using com.amazonaws.services.s3.AmazonS3 you can use a GetObjectMetadataRequest request which allows you to query the object length.
GetObjectMetadataRequest metadataRequest = new GetObjectMetadataRequest(bucketName, fileName);
final ObjectMetadata objectMetadata = s3Client.getObjectMetadata(metadataRequest);
long contentLength = objectMetadata.getContentLength();
Before you can execute the code above, you will need to build the S3 client. Here is some example code for that: