【问题标题】:Passing a txt file as an argument in JavaScript在 JavaScript 中将 txt 文件作为参数传递
【发布时间】:2017-11-12 06:28:04
【问题描述】:

我有以下代码:

function FileHandler() {

}

FileHandler.prototype.open = function(file) {
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
};

当我尝试在控制台中运行它时,我可以将本地文件作为文件所在的参数传递吗?如果我想这样做,我会使用什么语法?

【问题讨论】:

  • 这是在运行服务器端还是客户端?
  • 就在我的本地机器上,试图将一个txt文件的内容设置为一个变量。
  • 你应该在类似 node.js 的东西上运行这个脚本。如果您在浏览器中运行它,您将无法访问本地文件

标签: javascript


【解决方案1】:

您可以使用异步函数。

   FileHandler.prototype.open = function(file, callback) {
   var rawFile = new XMLHttpRequest();
   rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function() {
    if (rawFile.readyState == 4) {
        // The request is done; did it work?
        if (rawFile.status == 200) {
            // ***Yes, use `rawFile.responseText` here***
            callback(rawFile.responseText);
        } else {
            // ***No, tell the callback the call failed***
            callback(null);
        }
      }; 
    rawFile.open("GET", file, false);
    rawFile.send();
   };

【讨论】:

  • 谢谢,当我在 Chrome 的控制台中运行它时,如何将实际的 txt 文件作为参数传递?这可能吗?或者我只能在节点中执行此操作?
  • FileHandler.open('path-to-file', function(callback){/*callback 现在是文件*/}))
  • 好的,抱歉,花括号里会写什么?
  • 任何你想要的,或者什么都没有。
  • 加载时出现 xhr is not defined 错误,知道为什么会这样吗?
【解决方案2】:

http://www.creativebloq.com/web-design/read-local-files-file-api-121518548

它准确地展示了你如何做到这一点:

FileReader 对象允许我们一次读取文件的内容 我们从用户那里得到了一个文件。为安全起见,用户必须主动 给我们文件的引用,以便它可读。 有许多 FileReader 方法可以获取文件的 内容

这是一个如何使用它的示例:(来自网站的代码)

var reader = new FileReader();
//create our FileReader object to read the file

reader.addEventListener("load", fileRead, false);
//add an event listener for the onloaded event

function fileRead(event){
//called when the load event fires on the FileReader

var pictureURL = event.target.result;
//the target of the event is the FileReader object instance
//the result property of the FileReader contains the file contents
}

reader.readAsDataURL(file);
//when the file is loaded, fileRead will be called

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 2015-05-10
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多