You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在material-table中实现受控的文件上传按钮

实现代码

你可以直接修改document列的render配置,以下是完整可运行的修改后的列配置:

import { Button } from '@mui/material';

const columns = [
  {
    field: "truck_in_time",
    title: "入场时间",
    editable: "never",
  },
  {
    field: "truck_out_time",
    title: "离场时间",
    editable: "never",
  },
  {
    field: "document",
    title: "单据",
    width: 160,
    render: (params) => {
      // 文件选择后上传逻辑
      const handleFileUpload = async (e) => {
        const selectedFile = e.target.files[0];
        if (!selectedFile) return;

        const uploadData = new FormData();
        uploadData.append('file', selectedFile);
        // 可追加当前行的唯一标识用于后端关联数据
        uploadData.append('recordId', params.rowData.id);

        try {
          const response = await fetch('替换为你的后端上传接口地址', {
            method: 'POST',
            body: uploadData
          });
          const result = await response.json();
          // 上传成功后可在此处添加提示、刷新列表等逻辑
          console.log('上传成功', result);
        } catch (error) {
          console.error('上传失败', error);
        }
      };

      return (
        <>
          <input
            type="file"
            hidden
            id={`upload-input-${params.rowData.id}`}
            onChange={handleFileUpload}
          />
          <Button
            variant="outlined"
            color="primary"
            size="small"
            onClick={() => document.getElementById(`upload-input-${params.rowData.id}`).click()}
          >
            上传
          </Button>
        </>
      );
    },
    editable: "never",
  },
  {
    field: "remarks",
    title: "备注",
    width: 160,
    editable: "onUpdate",
  },
];

核心说明

  • 样式对齐:直接使用MUI官方的Button组件,参数和表格内置的编辑按钮保持一致,无需额外写CSS就能实现完全相同的视觉风格。
  • 文件选择逻辑:通过隐藏的原生input[type=file]触发系统文件选择弹窗,避免自定义交互带来的兼容性问题。
  • 上传逻辑:使用FormData格式封装文件和行关联信息,符合通用的文件上传接口规范,你可以根据自己的业务需求补充加载状态、结果提示、文件预览等扩展功能。

内容的提问来源于stack exchange,提问作者Raman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 03:12:00