Is there any way for a client to upload a file in an HTML form (e.g. .txt or .csv formats) to a JavaScript variable as a string using only JavaScript? If so, could you prov
This variation on yent's answer manages multiple uploads and uses jquery:
HTML:
script:
$("#myfile").on("change", function (changeEvent) {
for (var i = 0; i < changeEvent.target.files.length; ++i) {
(function (file) { // Wrap current file in a closure.
var loader = new FileReader();
loader.onload = function (loadEvent) {
if (loadEvent.target.readyState != 2)
return;
if (loadEvent.target.error) {
alert("Error while reading file " + file.name + ": " + loadEvent.target.error);
return;
}
console.log(loadEvent.target.result.length); // Your text is in loadEvent.target.result
};
loader.readAsText(file);
})(changeEvent.target.files[i]);
}
});
Worth noting:
The object is already busy reading
.i
value which ended the loop.This jsfiddle demo preserves upload order by laying out divs in the change handler.