Home > OS >  How to read content of uploaded json file on react / next.js
How to read content of uploaded json file on react / next.js

Time:04-25

My user will upload a json file with using this button (see below)

enter image description here

Then i will take this json file and pass the content of it to a variable (or a state).

let fileRef = useRef();

  const uploadHandler = async () => {
    await fileRef.click();
  };

  useEffect(() => {
    fileRef.addEventListener("change", () => {
      const file = fileRef.files[0];
      console.log(file);
    });
  }, []);

My console.log is looking like this,

enter image description here

CodePudding user response:

You need a file input, and and onChange event handler for the input, so when user upload a file, use the a new FileReader to read it.

import React, { useState } from "react";

export function Upload({ children }) {
  const [fileContent, setFileContent] = useState("");
  let fileRef = useRef();

  const readFile = event => {
    const fileReader = new FileReader();
    const { files } = event.target;

    fileReader.readAsText(files[0], "UTF-8");
    fileReader.onload = e => {
      const content = e.target.result;
      console.log(content);
      setFileContent(JSON.parse(content));
    };
  };

  return (
    <>
      <input ref={fileRef} type="file" onChange={readFile} />
      <button onClick={()=>fileRef.current.click()}>Upload<button/>
    </>
  );
}

CodePudding user response:

By using gray-matter

import matter from "gray-matter";
// set directory
const directory = path.join(process.cwd(), "src", "data", "uploads");

export function getJsonData(fileName) {
    // assuming that fileName has extension too
     const filePath = path.join(directory, `${fileName}`);
     const fileContent = fs.readFileSync(filePath, "utf-8");
     // data is the metadata
     const { data, content } = matter(fileContent);
     console.log("data",data)
     console.log("content",content)
     
}
  • Related