Skip to content

Instantly share code, notes, and snippets.

@jmdfm
Forked from cyberwombat/CORS Configuration
Created December 6, 2012 18:32
Show Gist options
  • Save jmdfm/4226852 to your computer and use it in GitHub Desktop.
Save jmdfm/4226852 to your computer and use it in GitHub Desktop.
JQuery file upload plugin (blueimp) with NodeJs Express3 directly to Amazon S3 with public access
crypto = require("crypto")
moment = require("moment") //requires >= 1.5.0 for UTC support
exports.upload = (req, res) ->
p = policy()
s = signature(p)
res.render "main/upload"
signature: s
policy: p
uid: uuid.v1()
aws_key: AWS_KEY
aws_bucket: AWS_BUCKET
signature = (policy) ->
crypto.createHmac("sha1", AWS_SECRET).update(policy).digest("base64")
policy = () ->
s3Policy =
{
expiration: moment.utc().add('minutes', 30).format('YYYY-MM-DDTHH:mm:ss\\Z')
conditions: [
{ bucket: settings.aws_img_bucket }
{ acl: "public-read-write" }
{ success_action_status: '201' }
["starts-with", "$key", ""]
["starts-with", "$Content-Type", "image/"]
]
}
new Buffer(JSON.stringify(s3Policy)).toString("base64")
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="/js/jquery.ui.widget.js"></script>
<script type="text/javascript" src="/js/jquery.fileupload.js"></script>
<script type="text/javascript">
$(function() {
$('#fileupload').fileupload({
url: 'https://{{ aws_bucket }}.s3.amazonaws.com/',
type: 'POST',
autoUpload: true,
}).bind('fileuploadsubmit', function (e, data) {
data.formData = {
"key": "${filename}",
"AWSAccessKeyId": "{{ aws_key }}",
"acl": "public-read-write",
"policy": "{{ policy }}",
"signature": "{{ signature }}",
"success_action_status": "201",
"Content-Type": data.files[0].type
}
})
});
</script>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" id="fileupload" name="file">
<input type="text" name="content-type" value="text/plain" />
<input type="submit" value="Save">
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment