Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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>
@simongfxu

This comment has been minimized.

Copy link

@simongfxu simongfxu commented Jul 21, 2014

awsome, just need it.thank you.

@simongfxu

This comment has been minimized.

Copy link

@simongfxu simongfxu commented Jul 22, 2014

if you are using a flash uploader, you should put a crossdomain.xml to you buckt and make it pulbic.

what's more, add a policy condition:

['starts-with', '$Filename', '']
@jontelm

This comment has been minimized.

Copy link

@jontelm jontelm commented Jan 24, 2015

https://github.com/bookingbricks/file-upload-example similar solution with aws-sdk-js.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment