Javascript从当前目录中读取文本文件 [英] Javascript read text file from current directory
问题描述
如何使用不带jquery的javascript从当前目录中读取文本文件(text1.txt)。我尝试了以下代码。
How to read text file (text1.txt) from current directory using javascript without jquery. I tried the following code.
var file = "text1.txt";
var reader = new FileReader();
var result = reader.readAsText(file);
console.log(result);
推荐答案
FileReader API通常用于读取通过选择的文件a < input type =file>
。它无法读取任意文件。 readAsText
方法期望使用Blob或File对象接收,而不是包含文件名的字符串。
The FileReader API is usually used to read files selected via the an <input type="file">
. It cannot read arbitrary files. The readAsText
method expects to receive with a Blob or a File object, not a string containing a file name.
要读取HTML文档的兄弟文件,使用 XMLHttpRequest 。如果通过HTTP(S)加载文档,这将可靠地工作。如果您使用的是本地HTML文档(通过文件:
URI),那么许多浏览器中的安全限制将阻止其工作(您应该运行本地Web服务器) 。
To read files that are siblings of the HTML document, use XMLHttpRequest. This will reliably work if you load the document over HTTP(S). If you are using a local HTML document (via a file:
URI) then security restrictions in many browsers will prevent it from working (and you should run a local web server instead).
这篇关于Javascript从当前目录中读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!