I am trying to read a text file using jquery, like this:
// LOAD file and split line by line and append divs
$.get(\'myFile.txt\', function(data) {
v
specify the full path of the file url
You can't do this without the WEB SERVER!!! Chrome sends XMLHttpRequest to the system that looks something like this
GET /myFile.txt HTTP/1.1
And the operating system is not listening on port 80 to receive this! And even if it is, it must implement HTTP protocol to communicate with the browser...
To get this working, you must have WEB SERVER installed on your system, that will listen on port 80 and make your files available through a HTTP connection, thus making your code runnable.
Something like this is what I use all the time. No need for any base64 decoding.
<html>
<head>
<script>
window.onload = function(event) {
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event) {
var fileReader = new FileReader();
fileReader.onload = function(event) {
$('#accessKeyField').val(event.target.result);
}
var file = event.target.files[0];
fileReader.readAsText(file);
document.getElementById('fileInput').value = null;
}
</script>
</head>
<body>
<input type="file" id="fileInput" style="height: 20px; width: 100px;">
</body>
</html>
A workaround for this I used was to include the data as a js file, that implements a function returning the raw data as a string:
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
<script type="text/javascript">
function loadData() {
// getData() will return the string of data...
document.getElementById('data').innerHTML = getData().replace('\n', '<br>');
}
</script>
</head>
<body onload='loadData()'>
<h1>check out the data!</h1>
<div id='data'></div>
</body>
</html>
// function wrapper, just return the string of data (csv etc)
function getData () {
return 'look at this line of data\n\
oh, look at this line'
}
See it in action here- http://plnkr.co/edit/EllyY7nsEjhLMIZ4clyv?p=preview
The downside is you have to do some preprocessing on the file to support multilines (append each line in the string with '\n\'
).