【Antd】基于 Upload 组件,导入Json文件并转换为Json数据

文章目录

组件封装

import { Upload, message } from 'antd';

export default function JsonFileImport({ onFileImport }) {
  // 处理文件选择变化
  const handleChange = (info) => {
    // 从info对象中获取原始的File对象:cite[5]
    const rawFile = info.file.originFileObj || info.file;

    if (rawFile) {
      // 1. 创建FileReader读取文件
      const reader = new FileReader();
      reader.onload = (event) => {
        try {
          // 2. 将读取到的文本解析为JSON对象
          const parsedData = JSON.parse(event.target.result);
          // 3. 抛到父组件处理json数据
          onFileImport(parsedData);
          message.success(`${rawFile.name} 文件读取成功`);
        } catch (error) {
          message.error(`${rawFile.name} 文件不是有效的JSON格式`);
          console.error('JSON解析错误:', error);
          onFileImport(null);
        }
      };
      reader.onerror = () => {
        message.error(`读取文件 ${rawFile.name} 失败`);
        onFileImport(null);
      };
      // 4. 开始以文本形式读取文件
      reader.readAsText(rawFile);
    }
  };
  const uploadProps = {
    accept: '.json,.jsonl', // 可选:限制只能选择.json文件:cite[1]
    beforeUpload: () => false, // 阻止自动上传,直接返回文件对象:cite[4]
    onChange: handleChange,
    showUploadList: false, // 不显示默认的文件列表
  };

  return <Upload {...uploadProps}>文件导入</Upload>;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一颗不甘坠落的流星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值