How to add a file to S3 via curl

One simple way to upload files to s3 bucket is to use a small bash script to do so. The following is an example bash script that should do the trick:

Bash Script (s3.sh):

#!/bin/bash
file="$1"
path="$2"

#change the following variables
AWSKey="[ENTER-YOUR-KEY-HERE]"
AWSSecret="[ENTER-YOUR-SECRET-HERE]"
bucket="[ENTER-YOUR-BUCKET-NAME]"
contentType="video/mp4"

#calculated information for the request
date="$(LC_ALL=C date -u +"%a, %d %b %Y %X %z")"
md5="$(openssl md5 -binary < "$file" | base64)"

# The next two lines has a line wrap on the website, should be one line
sig="$(printf "PUT\n$md5\n$contentType\n$date\n/$bucket/$path"
 | openssl sha1 -binary -hmac "$AWSSecret" | base64)"

responseCode=$(curl -T $file http://$bucket.s3.amazonaws.com/$path \
-H "Date: $date" \
-H "Authorization: AWS $AWSKey:$sig" \
-H "Content-Type: $content_type" \
-H "Content-MD5: $md5" --write-out \\n%{http_code} --silent)

echo $responseCode
if [ $responseCode = "200" ]
then
echo "Upload Successful"  
fi

Example:
sh ./s3.sh /path/to/local/file.mp4 relative/path/to/folder/in/bucket.mp4


Comments are closed.