How to change content type of Amazon S3 Objects

2020-02-06 05:59发布

The objects in my Amazon S3 bucket are all of the content type application/octet-stream. Some of these objects are PDFs, sometimes images like JPG, GIF, PNG. How can I change the content type of these objects to images/jpeg, application/pdf etc.?

Can it be done in batch through the Amazon Console?

Can I use the command line?

Or maybe through PHP?

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-02-06 06:29

You can use AWS sdk (php or other) I'll show how it works using CLI. To change content type on S3 given object, you need to copy this object and update the metadata information using the REPLACE tag so it copies to itself, you can achieve that using http://docs.aws.amazon.com/cli/latest/reference/s3api/copy-object.html

aws s3api copy-object --bucket <bucket_name> \
    --content-type "images/jpeg" \
    --copy-source <bucket_name>/path/to/images.jpeg \
    --key path/to/images.jpeg \
    --metadata-directive "REPLACE"
查看更多
▲ chillily
3楼-- · 2020-02-06 06:29

aws s3 ls s3://<YOUR_BUCKET> --recursive | awk '{print substr($0, index($0, $4))}' | grep <FILE_EXTENSTION> | while read -r line; do aws s3api copy-object --bucket <YOUR_BUCKET> --acl "<ACL_POLICY_IF_NEEDED>" --content-type "<REQUIRED_CONTENT_TYPE>" --copy-source "<YOUR_BUCKET>/$line" --key "$line" --metadata-directive "REPLACE"; done

This will do the trick. Breaking down the commands:

  • aws s3 ls s3://<YOUR_BUCKET> --recursive => This lists all files in your bucket
  • awk '{print substr($0, index($0, $4))}' => This will remove extra information like date and just give you all list of keys
  • grep <FILE_EXTENSTION> => This will filter the extension(say pdf/jpg) for which you want to update the content-type
  • while read -r line; do aws s3api copy-object --bucket <YOUR_BUCKET> --acl "<ACL_POLICY_IF_NEEDED>" --content-type "<REQUIRED_CONTENT_TYPE>" --copy-source "<YOUR_BUCKET>/$line" --key "$line" --metadata-directive "REPLACE"; done => This will replace all the filtered files in your bucket with the content-type you specify
查看更多
该账号已被封号
4楼-- · 2020-02-06 06:46

This is how you can set Content-Type for all files of type *.png

aws s3 cp \
       s3://BUCKET-NAME/ \
       s3://BUCKET-NAME/ \
       --exclude '*' \
       --include '*.png' \
       --no-guess-mime-type \
       --content-type="image/png" \
       --metadata-directive="REPLACE" \
       --recursive
查看更多
登录 后发表回答