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
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
Share Improve this question asked May 3, 2017 at 8:23 ngo cuongngo cuong 613 silver badges7 bronze badges 2-
Do you know if the click event being fired? i.e: have you put a
console.log
in the click function – Benji Lees Commented May 3, 2017 at 8:27 - See developer.mozilla/en-US/docs/Web/API/File/File – Benji Lees Commented May 3, 2017 at 8:29
2 Answers
Reset to default 4You 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).
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);
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742285643a4415271.html
评论列表(0条)