简体   繁体   English

使用HTML和Javascript读取本地纯文本文件

[英]Read local plain text file with HTML and Javascript

I have a text file containing some logging data from another (C++) application. 我有一个文本文件,其中包含来自其他(C ++)应用程序的一些日志记录数据。 As I don't want to use some GUI framework just to display some visual analysis of the logging data, I want to use HTML and Javascript to do this task. 由于我不想仅使用一些GUI框架来显示日志数据的可视化分析,因此我想使用HTML和Javascript来完成此任务。

I managed to input the data via a file input <input id="inputfile" type="file"/> and then read the file via FileReader in Javascript. 我设法通过文件输入<input id="inputfile" type="file"/>输入数据,然后通过Javascript中的FileReader读取文件。

My question: the logging file is in the same directory as the HTML+JS files and always has the same filename, it would be nice to read the file without having the user select the same file over and over again. 我的问题是:日志文件与HTML + JS文件位于同一目录中,并且始终具有相同的文件名,最好在不让用户反复选择同一文件的情况下读取该文件。 I could not manage to do this. 我无法做到这一点。 I tried <object id="data" type="text/plain" data="out.txt"></object> to include the logging file in the HTML and then read it via JS, but without success. 我尝试<object id="data" type="text/plain" data="out.txt"></object>将记录文件包含在HTML中,然后通过JS读取它,但没有成功。

Any ideas on how to avoid the user selection and always read the same (static) file when loading the document? 关于如何避免用户选择并在加载文档时始终读取相同(静态)文件的任何想法? If possible: (a.) by just using HTML, Javascript and jQuery. 如果可能的话:(a。)仅使用HTML,Javascript和jQuery。 (b.) without having to specify an absolute file path. (b。),而不必指定绝对文件路径。

There is another answer using XMLHttpRequest. 还有一个使用XMLHttpRequest的答案。 But as I said, I need a relative path and my data is plain text. 但是正如我所说,我需要一个相对路径,并且我的数据是纯文本。

you can not select a file with javascript without human interaction for security reasons but you can include in using a hidden iframe and then read the content of file like this 出于安全原因,您不能在没有人机交互的情况下使用javascript选择文件,但是您可以包括使用隐藏的iframe ,然后像这样读取文件的内容

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <iframe id="iframeId" src="data.text" frameborder="0" style="display:none"></iframe> <script> function readText() { var iframe = document.getElementById('iframeId'); var innerDoc = iframe.contentDocument || iframe.contentWindow.document; var text = innerDoc.getElementsByTagName('pre')[0].innerText; console.log(text); } setTimeout(function() { readText(); }, 50); </script> </body> </html> 

this will do the job but i am not sure if this is the best way to do it 这会做的工作,但我不确定这是否是最好的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM