Skip to content

Instantly share code, notes, and snippets.

@jeskew
Created May 19, 2017 17:15
Show Gist options
  • Save jeskew/6631c156b3cffc7adfe62c4cbc8cc9dc to your computer and use it in GitHub Desktop.
Save jeskew/6631c156b3cffc7adfe62c4cbc8cc9dc to your computer and use it in GitHub Desktop.
Presigned POST
const s3 = new AWS.S3({region: 'us-west-2'});
s3.createPresignedPost({
Bucket: 'bucket',
Fields: {
key: 'user_files/${filename}',
},
Conditions: [
['starts-with', '$key', '']
]
}, function (err, data) {
const form = document.createElement('form');
form.setAttribute('action', data.url);
form.setAttribute('method', 'POST');
form.setAttribute('enctype', 'multipart/form-data');
Object.keys(data.fields).forEach(function(key) {
const input = document.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('name', key);
input.setAttribute('value', data.fields[key]);
form.appendChild(input);
});
const fileInput = document.createElement('input');
fileInput.setAttribute('type', 'file');
fileInput.setAttribute('name', 'file');
form.appendChild(fileInput);
const submitButton = document.createElement('input');
submitButton.setAttribute('type', 'submit');
submitButton.setAttribute('name', 'submit');
submitButton.setAttribute('value', 'submit');
form.appendChild(submitButton);
document.getElementById('form-target').appendChild(form);
});
s3.createPresignedPost({
Expires: 60 * 60 * 24,
Bucket: 'my-bucket',
Fields: {
acl: 'public-read',
'x-amz-server-side-encryption': 'AES256',
'x-amz-meta-uuid': 'UUID',
},
Conditions: [
['starts-with', '$key', 'user/'],
["starts-with", "$Content-Type", "image/"],
['starts-with', '$x-amz-meta-tag', ''],
],
}, (err, data) => {
const form = new FormData();
const {fields, url} = data;
for (let field of Object.keys(fields)) {
form.append(field, fields[field]);
}
form.append('key', 'user/${filename}');
form.append('Content-Type', 'image/jpg');
form.append('x-amz-meta-tag', '');
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
xhr.send(data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment