Skip to content

Instantly share code, notes, and snippets.

@karlpokus
Last active March 21, 2017 08:24
Show Gist options
  • Save karlpokus/54eaecf5e82467c41aafef0b861bc390 to your computer and use it in GitHub Desktop.
Save karlpokus/54eaecf5e82467c41aafef0b861bc390 to your computer and use it in GitHub Desktop.
client file upload - closure and promises
// assume <input id="files" type="file" multiple/>
var files = document.getElementById('files');
files.addEventListener('change', processFiles, false);
function processFiles() {
readFiles(this.files, upload);
}
function readFiles(files, cb) {
var payloads = [];
for (var i = 0; i < files.length; i++) {
(function(file) {
var reader = new FileReader();
reader.onload = function(evt) {
payloads.push({
name: file.name,
file: evt.target.result,
ts: Date.now()
});
if (payloads.length === files.length) {
cb(payloads);
}
};
reader.readAsText(file);
})(files[i]);
}
}
function upload(payloads) {
var http = new XMLHttpRequest();
http.open('POST', '/data');
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
}
http.send(JSON.stringify(payloads));
}
// assume <input id="files" type="file" multiple/>
var files = document.getElementById('files');
files.addEventListener('change', processFiles, false);
function processFiles() {
var files = this.files,
fileList = [];
for (var i = 0; i < files.length; i++) {
fileList.push(readFile(files[i]));
}
Promise
.all(fileList)
.then(upload)
.catch(console.error);
}
function readFile(file) {
return new Promise(function(resolve, reject) {
var reader = new FileReader();
reader.onload = function(e) {
resolve({
name: file.name,
ts: Date.now(),
file: e.target.result
});
};
reader.onerror = reject;
reader.readAsText(file);
});
}
function upload(payloads) {
var http = new XMLHttpRequest();
http.open('POST', '/test');
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
}
http.send(JSON.stringify(payloads));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment