Created
July 5, 2023 00:13
-
-
Save codesnipers/2871fd3bf4c92581afaf9f7f859450a2 to your computer and use it in GitHub Desktop.
upload json read json antd
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from 'react'; | |
import { Upload, Button, message, Typography } from 'antd'; | |
import { UploadOutlined } from '@ant-design/icons'; | |
import axios from 'axios'; | |
const { Text } = Typography; | |
const UploadJSONComponent: React.FC = () => { | |
const [fileInfo, setFileInfo] = useState(null); | |
const [jsonObject, setJsonObject] = useState(null); | |
const handleFileUpload = async (file) => { | |
try { | |
const response = await axios.get(file.url); | |
const jsonData = response.data; | |
setJsonObject(jsonData); | |
} catch (error) { | |
console.error('Error reading file:', error); | |
} | |
}; | |
const handleFileChange = (info) => { | |
const file = info.file; | |
if (file.status === 'done') { | |
const reader = new FileReader(); | |
reader.onload = () => { | |
const content = reader.result; | |
setFileInfo({ name: file.name, content }); | |
}; | |
reader.readAsText(file.originFileObj); | |
} else if (file.status === 'error') { | |
message.error('File upload failed.'); | |
} | |
}; | |
return ( | |
<div> | |
<Upload | |
name="file" | |
action="/upload" | |
accept=".json" | |
showUploadList={false} | |
onChange={handleFileChange} | |
> | |
<Button icon={<UploadOutlined />}>Click to Upload JSON</Button> | |
</Upload> | |
{fileInfo && ( | |
<div> | |
<Text strong>File Name: </Text> | |
<Text>{fileInfo.name}</Text> | |
<br /> | |
<Text strong>File Content: </Text> | |
<pre>{fileInfo.content}</pre> | |
</div> | |
)} | |
{jsonObject && ( | |
<div> | |
<Text strong>JSON Object: </Text> | |
<pre>{JSON.stringify(jsonObject, null, 2)}</pre> | |
</div> | |
)} | |
</div> | |
); | |
}; | |
export default UploadJSONComponent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment