使用JavaScript读取本地文件

时间:2016-09-12 10:36:37

标签: javascript web file-read

所以我有一个本地名为" index.html"我使用"文件来访问://"协议。 (所以不是" http://"协议)。我需要访问一个文件" data.txt"在同一目录中,由一个单独的程序不断更改,但由于我使用文件协议,出于安全原因拒绝访问该文件。

我该怎么做才能阅读本地文件?我想过使用XAMPP或WAMP运行本地服务器,但我不想使用任何额外的程序。

编辑: 我不能使用输入文件,因为它应该在没有任何用户交互的情况下工作。

2 个答案:

答案 0 :(得分:0)

JavaScript是一种客户端渲染语言。对于某些安全问题,JavaScript不允许我们触摸客户端本地文件。即使页面来自本地文件系统,大多数浏览器也不允许您读取本地文件。

答案 1 :(得分:0)

您可以通过文件API - https://www.w3.org/TR/file-upload/

来完成

以下示例过滤掉用户选择的图片,调用文件上的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>
&#13;
&#13;
&#13;