Introduction

The Content-Type header is used to indicate the type of content that is being sent. This is useful for the browser to render the content correctly. For example, if the content is a text file, the browser will render it as a text file. If the content is an image, the browser will render it as an image.

If you are using AWS S3 to host your static website, you can set the Content-Type header for each file. This will ensure that the browser renders the content correctly.

In this tutorial, we will look at how we can use the AWS S3 CLI to set the content-type when uploading a file.

s3api put-object

We will use the s3api CLI command to upload a file to S3. The s3api command supports all of the functionality supported by AWS S3.put-object uploads an object to S3. You must have WRITE access to the bucket to be able to upload an object.

We will use the following parameters to upload a file to S3 with the Content-Type header set:

  • bucket (required): Name of the bucket where the object will be store
  • key (required): Key of the object to upload
  • body: File to upload
  • content-type: Content-Type header to set

We will use the following command to upload a file named index.html to S3 with the Content-Type header set to text/html:


aws s3api put-object --bucket bucket --key index.html --body index.html --content-type text/html

Verify the content-type

We can verify the content-type of the file by using the s3api head-object command. This command returns the metadata of the object.

aws s3api head-object --bucket bucket  --key index.html

Output:

{
    "AcceptRanges": "bytes",
    "LastModified": "2022-08-24T22:18:16+00:00",
    "ContentLength": 58,
    "ETag": "\"4409558fcf3eaf77a367cbf231698cbe\"",
    "VersionId": "null",
    "ContentType": "text/html",
    "Metadata": {}
}

Conclusion

In this tutorial, we looked at how we can use the AWS S3 CLI to set the content-type when uploading a file.