Reputation: 61
Javascript:
<script src="../plugin/jquery-3.1.0.min.js"></script>
<script>
$(document).ready(function(){
$('#test').click(function(){
var txtFile = '../fileupload/mail.txt';
var file = new File(txtFile);
file.open("r");
while (!file.eof) {
alert(file.readln());
}
file.close();
});
});
</script>
HTML:
<button type="submit" class="btn btn-default" id="test">Check</button>
When i click check button, Javascript will read file line by line. But it does not run :(. Please help me fix it
Upvotes: 0
Views: 7936
Reputation: 815
If you are looking to create and then download a file i would suggest that you take a look at file saver
var blob = new Blob(["r"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "mail.txt");
else if you are looking to upload a file I would add a input type="file" id="file-test"
and then use FileReader.
$('#file-test').change(function(e) {
var doc = event.target.files.document;
var reader = new FileReader();
reader.onload = function(event) {
// Then you can do something with the result
console.log(event.target.result)
};
reader.readAsText(doc);
}
Upvotes: 2
Reputation: 1073968
You cannot read files that way from browser-hosted JavaScript. The File
constructor doesn't accept just one argument, and File
objects don't have open
, readln
, or close
methods nor an eof
property. Whatever reference you're looking at, it's not for the browser-based File
object.
If you're running this from a proper web page, you can read resources from your own server via ajax (XMLHttpRequest
or fetch
).
If you're trying to read a local file, you'll have to have the user identify the file (you can't do it for them) via an input type="file"
, and then use the File API to read the contents of the file. This answer has an example of doing that (both in text and binary).
Upvotes: 4