[英]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)我的用户将使用此按钮上传一个 json 文件(见下文)
Then i will take this json file and pass the content of it to a variable (or a state).然后我将获取这个 json 文件并将其内容传递给变量(或状态)。
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,我的 console.log 看起来像这样,
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.您需要一个文件输入,以及输入的 onChange 事件处理程序,因此当用户上传文件时,使用新的 FileReader 来读取它。
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.