简体   繁体   English

从 HTML 文件输入中读取 JSON

[英]Read JSON from from HTML file input

If I have an input:如果我有输入:

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

And my user will upload a JSON file (as plaintext, so I will have to use JSON.parse() ), how can I take this file and actually get the data via getFile()我的用户将上传一个 JSON 文件(作为纯文本,所以我将不得不使用JSON.parse() ),我怎样才能获取这个文件并通过getFile()实际获取数据

In getFile(element) , I've tried using element.files[0] but that doesn't seem to contain the actual data.getFile(element)中,我尝试使用element.files[0] ,但这似乎不包含实际数据。 I've also looked here , here , and here , but none of these solve my problem.我也看过这里这里这里,但这些都不能解决我的问题。 This resource on MDN seems promising, but I don't really get it. MDN 上的这个资源看起来很有希望,但我真的不明白。

I would like a solution involving either URL.createObjectURL() or FileReader() .我想要一个涉及URL.createObjectURL()FileReader()的解决方案。

Also, before anyone posts this in the comments, I do understand that these solutions do not work on all browsers, and I would like to do this from the frontend.此外,在任何人在评论中发布此内容之前,我确实了解这些解决方案不适用于所有浏览器,我想从前端执行此操作。

You could take advantage of the Response constructor and call .json() on any blob/file.您可以利用Response构造函数并在任何 blob/文件上调用.json()

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

Alternative method using the new read methods on blob.prototype[...]使用 blob.prototype[...] 上的新读取方法的替代方法

new Blob(['1']).text().then(JSON.parse).then(console.log)

I guess for larger files response.json might be faster/better since it can parse the content in background and not block the main UI unlike JSON.parse我猜对于较大的文件响应。json 可能更快/更好,因为它可以解析后台内容并且不会像 JSON.parse 那样阻塞主 UI

I think you need this api:我想你需要这个 api:

FileReader Api From MDN 文件阅读器 Api 来自 MDN

JSON#parse() JSON#parse()

View In Stackblitz 在 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM