0

I have an input field in my React app where I can select/drag'n'drop files from my PC. The file data looks like this:

{
  path: "/test/metadata.json",
  lastModified: 1657787087977,
  name: "metadata.json",
  size: 10,
  type: "application/json",
  webkitRelativePath: ""
}

Having selected a file, I'm trying to perform a fetch request if the file is of type JSON in order to extract the contents.

acceptedFiles.forEach(file => {
      if (file.path.includes('.json')) {
        fetch(file.path)
          .then(res => res.json())
          .then(data => console.log(data));
      }
    });

The output of the fetch request above is this:

Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

And the request URL looks like it's trying to fetch the file from localhost:3000 and fails.

http://localhost:3000/test/metadata.json

My question: Is it possible to select some JSON file for upload and performs a fetch request on it in order to get its' contents? Can this be done in a React app or will I need Node.js for this?

Nora
  • 186
  • 2
  • 12
  • 1
    Say again, the file is *where* exactly in relation to the client (browser)? The user will select a JSON file (the one whose contents you show above), and inside that JSON file is the path to *another* JSON file also on the user's computer, and you're trying to read *that*? That's not going to work. The user has to explicitly select the file via an input element/drag'n'drop, you can't read arbitrary files from the user's harddisk. – deceze Sep 20 '22 at 06:36
  • 1
    one usually doesn't use `fetch` for a file that is dropped onto an input field - you would use the [FileReader API](https://developer.mozilla.org/en-US/docs/Web/API/FileReader) (scratch that, use the File API) – Jaromanda X Sep 20 '22 at 06:40
  • Note that the quoted file contents aren't JSON. JSON requires double quotes around property names. – T.J. Crowder Sep 20 '22 at 07:28

1 Answers1

-2

Seems like the JSON data is not valid. JSON data should be like this:

    {
      "path": "/test/metadata.json",
      "lastModified": 1657787087977,
      "name": "metadata.json",
      "size": 10,
      "type": "application/json",
      "webkitRelativePath": ""
    }
Raiyad Raad
  • 482
  • 5
  • 17