Skip to content

Instantly share code, notes, and snippets.

@franzwong
Created June 16, 2019 04:49
Show Gist options
  • Save franzwong/e417168f49298048fa552c02d1c0d487 to your computer and use it in GitHub Desktop.
Save franzwong/e417168f49298048fa552c02d1c0d487 to your computer and use it in GitHub Desktop.
S3 POST policy example
const AWS = require('aws-sdk');
const s3 = new AWS.S3({apiVersion: '2006-03-01'});
const uuidv4 = require('uuid/v4');
const bucketName = process.env.bucketName;
const kmsKeyId = process.env.kmsKeyId;
const MAX_FILE_SIZE = 5 * 1024 * 1024;
const EXPIRATION = 900;
const OBJECT_ACL = 'bucket-owner-full-control';
const generateHtml = (presignedPost) => {
const fields = Object.entries(presignedPost.fields).reduce((accumulator, currentValue) =>
accumulator + ` <input type="hidden" name="${currentValue[0]}" value="${currentValue[1]}">\n`
, '');
return `
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<form action="${presignedPost.url}" method="post" enctype="multipart/form-data">
${fields}
<input type="hidden" name="key" value="test-file-upload">
<div><input type="file" name="file"></div>
<input type="submit" name="submit" value="Upload" />
</form>
</html>
`;
}
exports.handler = async () => {
try {
const objectKey = uuidv4();
// Make sure IAM role assigned to Lambda has the right to write S3 bucket and KMS key
const presignedPost = s3.createPresignedPost({
Bucket: bucketName,
Conditions: [
['content-length-range', 0, MAX_FILE_SIZE],
],
Fields: {
'acl': OBJECT_ACL,
'key': objectKey,
// Server side encryption is optional
'x-amz-server-side-encryption': 'aws:kms',
'x-amz-server-side-encryption-aws-kms-key-id': kmsKeyId,
},
Expires: EXPIRATION
});
// Generate HTML can even be used in local machine
return generateHtml(presignedPost);
} catch (err) {
console.error(`Error: ${err}`);
throw err;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment