0

I want to get to know the size of a file to decide if I'm going to make a GET request to download it or not. The file is in my AWS S3 Bucket.

I know that it is a good idea to make a HEAD request to the same URL, so it returns me the "Content-Length", although it is not avaliable by my frontend (javascript code running at the browser)

I've read that I need to set the header below to the HEAD response:

"Access-Control-Expose-Headers": "Content-Length"

I've also found out that I could use Lambda@Edge to add this header to the response, but I'm not using Cloudfront to serve this file. By triggering Lambda@Edge directly from S3 (as an event), I could not find a way to handle HEAD requests, only PUT, POST and DELETE in there.

Any ideas to include this header?

1 Answers1

1

The entire question revolves around Cross-Origin Resource Sharing -- CORS. For this, you need to enable CORS support on your bucket.

See https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html.

Specifically, the <ExposeHeader> directive specifies headers that will appear in the Access-Control-Expose-Headers response header that S3 will generate, with CORS enabled and configured.

For example:

<CORSConfiguration>
 <CORSRule>

  <AllowedOrigin>https://www.example.com</AllowedOrigin>
   <AllowedMethod>HEAD</AllowedMethod>
   <AllowedHeader>*</AllowedHeader>
   <ExposeHeader>Content-Length</ExposeHeader>
 </CORSRule>
</CORSConfiguration>

Note also that this is incorrect:

By triggering Lambda@Edge directly from S3 (as an event)

Lambda functions can be triggered from S3 events, but using Lambda@Edge to examine or modify requests or responses is unrelated to S3 events, and is only possible in CloudFront.

Michael - sqlbot
  • 169,571
  • 25
  • 353
  • 427