2

我正在尝试解析本地目录中的一些数据。我使用 papa 解析器来做到这一点。问题是我无法将文本文件分配给变量。我收到此错误;

未捕获的 TypeError:无法在“FileReader”上执行“readAsText”:参数 1 不是“Blob”类型。

我已经对其进行了搜索,并且发现使用 HTML file reader 读取文件时这是一个非常常见的错误。

我的代码是;

<!doctype html>
<html class="no-js" lang="">
    <head>
        <script src="https://github.com/mholt/PapaParse/blob/master/papaparse.js"></script>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Parse Example</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
        <script src="js/vendor/modernizr-2.8.3.min.js"></script>
    </head>
    <p>Click the button to Upload .</p>
    <button onclick="myFunction()" type="INPUT">Load</button>
    <input type="file" name="datafile" size="40">
    <script>
        var x;
        var config = {
            delimiter: "",	// auto-detect
            newline: "",	// auto-detect
            header: true,
            dynamicTyping: false,
            preview: 0,
            encoding: "",
            worker: false,
            comments: false,
            step: undefined,
            complete: undefined,
            error: undefined,
            download: true,
            skipEmptyLines: false,
            chunk: undefined,
            fastMode: undefined,
            beforeFirstChunk: undefined,
            withCredentials: undefined
        };
        function myFunction() {
            x = document.getElementsByName("datafile");
            myfile =  Papa.parse(x, config);
            document.getElementById("demo").innerHTML = myfile;
        }
    </script>
    <p id="demo"></p>
    </body>
</html>

4

1 回答 1

3
  1. getElementsByNamereturn 总是返回匹配元素的 nodelist 集合,所以基本上你可以选择第一个:x = document.getElementsByName("datafile")[0]

  2. Papa.parse期望它的第一个参数是字符串或File对象。File可以从 中获取对象FileList,该对象存储在files文件输入的属性中。所以基本上(如果在输入中选择了文件,它应该可以工作): x = document.getElementsByName("datafile")[0].files[0]

  3. 正如documentaion所说Papa.parse,它本身不会返回任何东西,您应该提供回调来获取数据。所以如果你用类似的东西complete: undefined替换对象config

    complete: function(data) {
        console.log(data);
    }
    

    您将在浏览器控制台中显示您的数据。

于 2016-06-20T12:19:29.240 回答