Skip to content

Instantly share code, notes, and snippets.

@christophercliff
Created February 11, 2013 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christophercliff/4758164 to your computer and use it in GitHub Desktop.
Save christophercliff/4758164 to your computer and use it in GitHub Desktop.
Upload files directly to Amazon S3 from the browser using HTTP POST. Generate policy and signature using an express.js server (node.js).
// Requires underscore.js and jquery.js
$.ajax({
type: 'GET',
url: 'http://your-server.com/signature',
success: function(response){
var data = new FormData();
_.each(response.fields, function(val, key){
data.append(key, val);
});
data.append('file', yourFile);
$.ajax({
type: 'POST',
url: response.url,
data: data,
processData: false,
contentType: false
});
},
dataType: 'json'
});
var express = require('express'),
http = require('http'),
path = require('path'),
crypto = require('crypto'),
moment = require('moment'),
uuid = require('node-uuid');
var app = express();
// Your express config, etc.
var publicKey = 'YOUR_PUBLIC_KEY';
var privateKey = 'YOUR_PRIVATE_KEY';
var bucket = 'YOUR_BUCKET';
var uploadDir = 'uploads/';
var mimetype = 'image/png';
var acl = 'public-read';
var policy = new Buffer(JSON.stringify({
'expiration': moment().add('minutes', 5).utc().format('YYYY-MM-DDTHH:mm:ss') + 'Z',
'conditions': [
{ 'bucket': bucket },
[ 'starts-with', '$key', uploadDir ],
{ 'acl': acl },
[ 'eq', '$Content-Type', mimetype ],
[ 'content-length-range', 0, 10490000 ],
]
})).toString('base64');
var signature = crypto.createHmac('sha1', privateKey).update(policy).digest('base64');
app.get('/signature', function(req, res){
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
url: 'https://' + bucket + '.s3.amazonaws.com/',
fields: {
key: uploadDir + uuid.v4() + '.png',
AWSAccessKeyId: publicKey,
acl: acl,
'Content-Type': mimetype,
policy: policy,
signature: signature
}
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment