使用Javascript读取本地文本文件 [英] Read a local text file using Javascript
问题描述
我已经阅读了有关此主题的一些先前问题,但我确实需要100%确定!
I have read some of the previous questions on this topic but I really need to be 100% sure!
是否可以从.txt文件中读取我的本地系统并将其呈现在我的HTML-BODY中?
Is it possible to read from a .txt file on my local system and present it in my HTML-BODY?
我尝试了几个函数,这里有一个:
I have tried several functions, here is one:
function readFile (path) {
var fso = new ActiveXObject('Scripting.FileSystemObject'),
iStream=fso.OpenTextFile(path, 1, false);
while(!iStream.AtEndOfStream) {
document.body.innerHTML += iStream.ReadLine() + '<br/>';
}
iStream.Close();
}
readFile("testing.txt");
文件的内容只是我要从文本文件中读取的大约100个单词并显示在我的HTML-BODY。
The content of the file is simply around 100 words I want to read from the text file and display in my HTML-BODY.
这可能没有我自己的服务器吗?
Is this possible without having my own server?
推荐答案
您可以使用 FileReader
对象来读取文本文件,这里是示例代码:
You can use a FileReader
object to read text file here is example code:
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
</script>
这是codepen demo
Here is the codepen demo
如果每次加载应用程序时都有一个固定文件,那么您可以使用以下代码:
If you have a fixed file to read every time your application load then you can use this code :
<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
fileDisplayArea.innerText = allText
}
}
}
rawFile.send(null);
}
readTextFile("file:///C:/your/path/to/file.txt");
</script>
这篇关于使用Javascript读取本地文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!