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?
>Solution :
If you have a File object (from drag-and-drop or similar), there’s no need to use fetch (and in fact you can’t; you don’t have a URL for the file, and the file is coming from the file system, not from a server). Instead, for a JSON file, you’d use the text method File inherits from Blob. You seem to have an array of files, so:
Promise.all(acceptedFiles.map(
(file) => file.text().then((text) => JSON.parse(text))
))
.then((results) => {
// ...use `results` here, it's an array with the parsed contents
// of each file as its elements...
})
.catch((error) => {
// ...handle/report error...
});
Blob has other methods you can use such as stream to get a stream of the file’s contents, or arrayBuffer to read its contents into an ArrayBuffer you can then use with a typed array (such as a Uint8Array). But for JSON, text is the method you’d want.