简体   繁体   中英

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

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

在此处输入图像描述

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,

在此处输入图像描述

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/>
    </>
  );
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM