Home > Net >  How to get the content of an uploaded JSON in React
How to get the content of an uploaded JSON in React

Time:09-21

There is a component for drag and drop which supports adding multiple files.

When a file is added it must show the content of that file (a JSON file) but it doesn't work.

Here is the code:

  if (files?.length) {
    const test = files[0];
    console.log('files[0]: ', test);
    // lastModified: 1663321587219
    // lastModifiedDate: Fri Sep 16 2022 12:46:27 GMT 0300 (Eastern European Summer Time) {}
    // name: "oam-license.json"
    // size: 307
    // type: "application/json"
    // webkitRelativePath: ""
    console.log('typeof test: ', typeof test);
    // object
  }

How can the JSON content be viewed?

CodePudding user response:

You are working with raw File objects. You need to read the content of the file, which can be achieved using the text() method:

if (files?.length) {
    const test = files[0];
    test.text().then(result => {
        console.log(result)
        // if you want to work with the JSON data, you can also parse its content
        const json = JSON.parse(result)
    })
}
  • Related