adding csv uploader with webworkers
This commit is contained in:
25
attachments/script/costco-csv-worker.js
Normal file
25
attachments/script/costco-csv-worker.js
Normal file
@@ -0,0 +1,25 @@
|
||||
importScripts('lib/underscore.js');
|
||||
|
||||
onmessage = function(message) {
|
||||
var rows = message.data.data.split('\n');
|
||||
var docs = [];
|
||||
_.each(rows, function(row) {
|
||||
if (row.length == 0) return;
|
||||
var doc = {};
|
||||
_.each(row.split(','), function(field, index) { doc['field' + index] = field });
|
||||
docs.push(doc);
|
||||
})
|
||||
var req = new XMLHttpRequest();
|
||||
req.onreadystatechange = function() {
|
||||
if (req.readyState == 4) postMessage(JSON.stringify({done: true}))
|
||||
};
|
||||
req.onprogress = function(e) {
|
||||
if (e.lengthComputable) {
|
||||
var percentComplete = (e.loaded / e.total) * 100;
|
||||
postMessage(JSON.stringify({percent: percentComplete}));
|
||||
}
|
||||
}
|
||||
req.open('POST', message.data.url);
|
||||
req.setRequestHeader('Content-Type', 'application/json');
|
||||
req.send(JSON.stringify({docs: docs}));
|
||||
};
|
||||
@@ -103,6 +103,35 @@ var costco = function() {
|
||||
}
|
||||
return updateDocs(deleteFunc);
|
||||
}
|
||||
|
||||
function uploadCSV() {
|
||||
util.notify('Upload started.');
|
||||
var file = $('#file')[0].files[0];
|
||||
if (file) {
|
||||
var reader = new FileReader();
|
||||
reader.readAsText(file);
|
||||
reader.onload = function(event) {
|
||||
util.notify('File loaded.');
|
||||
var payload = {
|
||||
url: window.location.href + "/api/_bulk_docs", // todo more robust url composition
|
||||
data: event.target.result
|
||||
};
|
||||
var worker = new Worker('script/costco-csv-worker.js');
|
||||
worker.onmessage = function(message) {
|
||||
if(JSON.parse(message.data).done) {
|
||||
util.notify("Data uploaded successfully!");
|
||||
recline.initializeTable(app.offset);
|
||||
util.hide('dialog');
|
||||
} else {
|
||||
util.notify(message.data);
|
||||
}
|
||||
};
|
||||
worker.postMessage(payload);
|
||||
};
|
||||
} else {
|
||||
util.notify('File not selected. Please try again');
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
evalFunction: evalFunction,
|
||||
@@ -111,6 +140,7 @@ var costco = function() {
|
||||
updateDocs: updateDocs,
|
||||
uploadDocs: uploadDocs,
|
||||
deleteColumn: deleteColumn,
|
||||
ensureCommit: ensureCommit
|
||||
ensureCommit: ensureCommit,
|
||||
uploadCSV: uploadCSV
|
||||
};
|
||||
}();
|
||||
Reference in New Issue
Block a user