Created
October 17, 2016 15:29
-
-
Save pigoz/ae19808c277d6d3e8ba360338de96c41 to your computer and use it in GitHub Desktop.
AWS S3 Presigned Post upload in JavaScript with FormData
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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