applemonkey496
applemonkey496

Reputation: 743

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()

In getFile(element), I've tried using element.files[0] but that doesn't seem to contain the actual data. 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.

I would like a solution involving either URL.createObjectURL() or 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.

Upvotes: 1

Views: 3445

Answers (2)

Endless
Endless

Reputation: 37855

You could take advantage of the Response constructor and call .json() on any blob/file.

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[...]

new Blob(['1']).text().then(JSON.parse).then(console.log)
// handles emptying file input with ?.
elm.files[0]?.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

Upvotes: 6

itning
itning

Reputation: 170

I think you need this 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>

Upvotes: 2

Related Questions