首页 > 解决方案 > 在 Mac OS 上通过 javascript 读取文本文件

问题描述

我想通过 javascript 读取本地文本文件。我从如何读取本地文本文件中复制了代码?

但它不工作。

这是代码片段,

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;
                alert(allText);
            }
        }
    }
    console.log(rawFile);
     rawFile.send(null);
}

readTextFile("file:///Users/vivek/Desktop/file1.txt");

我尝试打印对象(rawFile),这是我得到的输出,

[object XMLHttpRequest] {
  abort: function abort() { [native code] },
  addEventListener: function addEventListener() { [native code] },
  dispatchEvent: function dispatchEvent() { [native code] },
  DONE: 4,
  getAllResponseHeaders: function getAllResponseHeaders() { [native code] },
  getResponseHeader: function getResponseHeader() { [native code] },
  HEADERS_RECEIVED: 2,
  LOADING: 3,
  onabort: null,
  onerror: null,
  onload: null,
  onloadend: null,
  onloadstart: null,
  onprogress: null,
  onreadystatechange: function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    },
  ontimeout: null,
  open: function open() { [native code] },
  OPENED: 1,
  overrideMimeType: function overrideMimeType() { [native code] },
  readyState: 1,
  removeEventListener: function removeEventListener() { [native code] },
  response: "",
  responseText: "",
  responseType: "",
  responseURL: "",
  responseXML: null,
  send: function send() { [native code] },
  setRequestHeader: function setRequestHeader() { [native code] },
  status: 0,
  statusText: "",
  timeout: 0,
  UNSENT: 0,
  upload: [object XMLHttpRequestUpload] {
    addEventListener: function addEventListener() { [native code] },
    dispatchEvent: function dispatchEvent() { [native code] },
    onabort: null,
    onerror: null,
    onload: null,
    onloadend: null,
    onloadstart: null,
    onprogress: null,
    ontimeout: null,
    removeEventListener: function removeEventListener() { [native code] }
  },
  withCredentials: false
}

readyState 的值为 1,所以我尝试将条件更改if(rawFile.readyState === 4)if(rawFile.readyState === 1),但仍然没有运气。

这是错误,我正在使用 JSBin,

"error"
"Error: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///Users/vivek/Desktop/file1.txt'.
    at readTextFile (gazoqoq.js:18:14)
    at gazoqoq.js:21:1
    at https://static.jsbin.com/js/prod/runner-4.1.4.min.js:1:13924
    at https://static.jsbin.com/js/prod/runner-4.1.4.min.js:1:10866"

标签: javascriptfilexmlhttprequesthttprequestonreadystatechange

解决方案


推荐阅读