从 HTML 文件输入中读取 JSON

Read JSON from from HTML file input

如果我有一个输入:

<input type="file" id="upload" onchange="getFile(this)">

我的用户将上传一个 JSON 文件(作为明文,所以我将不得不使用 JSON.parse()),我怎样才能拿到这个文件并通过 [=14= 实际获取数据]

getFile(element) 中,我尝试使用 element.files[0],但它似乎不包含实际数据。我也在 MDN 上看过 here, here, and , but none of these solve my problem. This resource 似乎很有前途,但我真的不明白。

我想要一个涉及 URL.createObjectURL()FileReader() 的解决方案。

此外,在任何人在评论中发布此内容之前,我确实了解这些解决方案并不适用于所有浏览器,我想从前端执行此操作。

我想你需要这个api:

FileReader Api From MDN

JSON#parse()

View In Stackblitz

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Read Text</title>
  <style>
    div {
     margin-top: 30px;
     border: solid 1px black;
     padding: 5px;
    }
  </style>
  <script>
    function processFiles(files) {
      var file = files[0];

      var message = document.getElementById("message");
      message.innerHTML = "File Name:" + file.name + "<br>";
      message.innerHTML += "File Size:" + file.size + "<br>";
      message.innerHTML += "File Type:" + file.type + "<br>";

      var reader = new FileReader();
      reader.onload = function (e) {
        var output = document.getElementById("fileOutput");  
        // parse string to json 
        output.textContent = JSON.parse(e.target.result);
      };
      reader.readAsText(file);
    }
  </script>
</head>
<body>
  <input id="fileInput" type="file" size="50" onchange="processFiles(this.files)">
  <div id="message"></div>
  <div id="fileOutput"></div>
</body>
</html>

您可以利用 Response 构造函数并在任何 blob/file.

上调用 .json()
function getFile (elm) {
  new Response(elm.files[0]).json().then(json => {
    console.log(json)
  }, err => {
    // not json
  })
}

在 blob.prototype[...]

上使用新读取方法的替代方法
new Blob(['1']).text().then(JSON.parse).then(console.log)

我猜对于较大的文件 response.json 可能是 faster/better 因为它可以在后台解析内容而不是阻塞主 UI 不像 JSON.parse