Skip to content

Instantly share code, notes, and snippets.

@juanlu-sanz
Created April 21, 2014 17:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save juanlu-sanz/11150341 to your computer and use it in GitHub Desktop.
Save juanlu-sanz/11150341 to your computer and use it in GitHub Desktop.
Read a .txt file from Javascript automatically using Filereader. useful for previews before uploading.
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Automatic line reading snippet</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
</head>
<body>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<input type="file" id="files" name="file"/>
<div id="file_content">
<ul></ul>
</div>
<script>
function readBlob() {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
if (file.type.localeCompare("text/plain")!==0) {
alert('Please upload a text file!');
return;
}
if (file.size > 1024*5) {
alert('File is larger than 5KB!');
return;
}
var reader = new FileReader();
var unorderedList = document.getElementById('file_content').getElementsByTagName("ul")[0];
// Removing all previous children from the unordered list (in case we upload a second file)
while (unorderedList.firstChild) {
unorderedList.removeChild(unorderedList.firstChild);
}
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
var lineArray = evt.target.result.match(/[^\r?\n]+/g);
for (var i = lineArray.length - 1; i >= 0; i--) {
var li = document.createElement("li");
li.textContent = lineArray[i];
unorderedList.appendChild(li)
};
}
};
var blob = file.slice(0, file.size);
reader.readAsText(blob);
}
document.querySelector('#files').addEventListener('change', function(evt) {
if (evt.target.tagName.toLowerCase() == 'input') {
readBlob();
}
}, false);
</script>
</body>
</html>
@juanlu-sanz
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment