简体   繁体   English

使用 JavaScript 读取本地文件

[英]Reading local file using JavaScript

So i have a file locally called "index.html" which i access using the "file://" protocol.所以我在本地有一个名为“index.html”的文件,我使用“file://”协议访问它。 (So not the "http://" protocol). (所以不是“http://”协议)。 I need to access a file "data.txt" in the same directory which is continuously changed by a seperate program, but since i'm using the file protocol the access to the file is denied for security reasons.我需要访问同一目录中的文件“data.txt”,该文件由单独的程序不断更改,但由于我使用的是文件协议,因此出于安全原因拒绝访问该文件。

What could i do to read the local file?我该怎么做才能读取本地文件? I thought of running a local server using XAMPP or WAMP but i'd rather not use any extra programs.我想过使用 XAMPP 或 WAMP 运行本地服务器,但我不想使用任何额外的程序。

EDIT: I cannot use an input file, since it should work without any user interaction.编辑:我不能使用输入文件,因为它应该在没有任何用户交互的情况下工作。

You may do it via the File API - https://www.w3.org/TR/file-upload/您可以通过文件 API - https://www.w3.org/TR/file-upload/

The example below filters out images from the user's selection, calls reader.readAsDataURL() on the file, and renders a thumbnail by setting the 'src' attribute to a data URL.下面的示例从用户的选择中过滤掉图像,对文件调用 reader.readAsDataURL(),并通过将 'src' 属性设置为数据 URL 来呈现缩略图。

 <style> .thumb { height: 75px; border: 1px solid #000; margin: 10px 5px 0 0; } </style> <input type="file" id="files" name="files[]" multiple /> <output id="list"></output> <script> function handleFileSelect(evt) { var files = evt.target.files; // FileList object // Loop through the FileList and render image files as thumbnails. for (var i = 0, f; f = files[i]; i++) { // Only process image files. if (!f.type.match('image.*')) { continue; } var reader = new FileReader(); // Closure to capture the file information. reader.onload = (function(theFile) { return function(e) { // Render thumbnail. var span = document.createElement('span'); span.innerHTML = ['<img class="thumb" src="', e.target.result, '" title="', escape(theFile.name), '"/>'].join(''); document.getElementById('list').insertBefore(span, null); }; })(f); // Read in the image file as a data URL. reader.readAsDataURL(f); } } document.getElementById('files').addEventListener('change', handleFileSelect, false); </script>

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

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