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
You can't load a file from your local filesystem, like this, you need to put it on a a web server and load it from there. On the same site as you have the JavaScript loaded from.
EDIT: Looking at this thread, you can start chrome using option --allow-file-access-from-files
, which would allow access to local files.
If you include a file input box you can access the file as a base64 encoded string by using the FileReader object. If it's a text file a simple base64 decode will work to get the text.
Assuming the following HTML:
<input type="file" id="myfile" />
You can access using the following JQuery JS:
var file = $('#myfile').get(0).files[0];
var reader = new FileReader();
reader.onload = function (e) {
//get the file result, split by comma to remove the prefix, then base64 decode the contents
var decodedText = atob(e.target.result.split(',')[1]);
//show the file contents
alert(decoded);
};
reader.readAsDataURL(file);
This doesn't work and it shouldn't because it would be a giant security hole.
Have a look at the new File System API. It allows you to request access to a virtual, sandboxed filesystem governed by the browser. You will have to request your user to "upload" their file into the sandboxed filesystem once, but afterwards you can work with it very elegantly.
While this definitely is the future, it is still highly experimental and only works in Google Chrome as far as CanIUse knows.
This is working fine in firefox at least.
The problem I was facing is, that I got an XML object in stead of a plain text string. Reading an xml-file from my local drive works fine (same directory as the html), so I do not see why reading a text file would be an issue.
I figured that I need to tell jquery to pass a string in stead of an XML object. Which is what I did, and it finally worked:
function readFiles()
{
$.get('file.txt', function(data) {
alert(data);
}, "text");
}
Note the addition of '"text"' at the end. This tells jquery to pass the contents of 'file.txt' as a string in stead of an XML object. The alert box will show the contents of the text file. If you remove the '"text"' at the end, the alert box will say 'XML object'.
As long as the file does not need to be dynamically generated, e.g., a simple text or html file, you can test it locally WITHOUT a web server - just use a relative path.
this one is working
$.get('1.txt', function(data) {
//var fileDom = $(data);
var lines = data.split("\n");
$.each(lines, function(n, elem) {
$('#myContainer').append('<div>' + elem + '</div>');
});
});