Skip to content

Instantly share code, notes, and snippets.

@pigoz
Created October 17, 2016 15:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pigoz/ae19808c277d6d3e8ba360338de96c41 to your computer and use it in GitHub Desktop.
Save pigoz/ae19808c277d6d3e8ba360338de96c41 to your computer and use it in GitHub Desktop.
AWS S3 Presigned Post upload in JavaScript with FormData
post = Aws::S3:Bucket.new('XXXXX').presigned_post(
key: "uploads/tmp/#{SecureRandom.uuid}/${filename}",
success_action_status: '201',
acl: 'public-read')
{ url: post.url.to_s, fields: post.fields }.to_json
/* global FormData, XMLHttpRequest, DOMParser */
const makeForm = (file, token) => {
const form = new FormData();
Object.keys(token.fields).forEach(k => {
const v = token.fields[k];
form.append(k, v);
});
form.append('file', file);
return form;
};
type Map<K, V> = { [key: K]: V };
// result of presigned post Aws::S3::Bucket.presigned_post API call
type TokenT = {
url: ?string,
fields: Map<string, any>,
};
// file is a web api File
const upload = (file, token: TokenT, cb = {}) =>
new Promise((resolve, reject) => {
const fd = makeForm(file, token);
const xhr = new XMLHttpRequest();
xhr.onload = () => {
if (xhr.status !== 201) {
reject();
}
const xml = new DOMParser().parseFromString(xhr.responseText, 'text/xml');
const url = xml.querySelector('Location').firstChild.nodeValue;
resolve(url);
};
xhr.onerror = reject;
xhr.upload.onprogress = (event) => {
if (event.lengthComputable && cb.onprogress) {
const percent = Math.round((event.loaded / event.total) * 100);
cb.progess(percent, event.loaded, event.total);
}
};
xhr.open('POST', token.url, true);
xhr.send(fd);
}); // Promise
export default upload;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment