Working with http headers for images in S3 environment

Contributed by uttam on 15 Nov 2011

This instance, I came across a situation where the client had many images loaded to S3 bucket and we were downloading as usual everyone does for viewing.

One of the request that came up was how do we add some performance to this step of viewing images, So AWS api were dug into and before that google was called for help. Many wonderful tools have been created out there which will help us achieve this without code, one of the tools was S3 Bucket (BTW I love the concept of Amazon buckets). You can download a free version of this tool and  keep doing your put / get /modify very easily but that was no fun !.  There is one more helpful product S3cmd , very wisely it looks like a cmd of most of the operating system, it provides many features including setting ACL, moving contents in and out of the buckets, the elegance of this product is that it matches most of the unix help features s3cmd -help and it will pour out information of tasks that can be done easily.  

One of the feature wherein we can have a page load faster is by setting http Expires header on the images, Since our code was already in java we followed it to get the work done, this is for any new images to be uploaded with http Expires header.

Here is a code snippet for the same:

   key = contentId+”/”+file.getName();
   ObjectMetadata obj = new ObjectMetadata();
   obj.setHeader(“Expires”,formatDate(new Date(new Date().getTime() + YEAR_MILLISECONDS))); /* this line does the needful */
   InputStream inputStream = new FileInputStream(file);
   amazonS3.putObject(new PutObjectRequest(bucket, key, inputStream, obj));

ObjectMetadata comes with Amazon jar viz :  aws-java-sdk-1.2.1.jar.

there are verious methods and languages to achive the same, example using REST API, Amazon Tools, etc this however solves the appetite of putting http headers to images in S3 bucket using  java.

Visit us at to know more about our offerings.

Leave a Comment

Security Code: