当前位置:首页 > 随笔 > 正文内容

Ant Design 自定义文件上传组件

访客 随笔 2026年6月25日 1

为了在 Ant Design 的表单中实现自定义文件上传功能,可以通过封装一个独立的上传组件,并将其与表单字段(FormItem)集成。以下代码展示了如何实现这一功能。

首先,创建一个名为 CustomFileUploader 的 React 组件:

import React from 'react';
import { Upload, Button, message } from 'antd';
import { uploadService, queryService } from '@/services/fileUpload';

class CustomFileUploader extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      uploadedFiles: [],
      fileRecords: []
    };
    this.isInitialValueEmpty = true;
  }

  componentDidMount() {
    this.syncWithInitialValue();
  }

  syncWithInitialValue = () => {
    const { initialValue } = this.props['data-__meta'] || {};
    if (initialValue !== this.currentInitialValue) {
      this.handleInitialValueChange(initialValue);
    }
    this.currentInitialValue = initialValue;
  };

  handleInitialValueChange = (value) => {
    if (value) {
      this.fetchFileDetails(value.split(','));
    } else if (!this.isInitialValueEmpty) {
      this.resetState();
    }
  };

  fetchFileDetails = (fileIds) => {
    fileIds.forEach((id) => {
      if (!this.state.uploadedFiles.includes(id)) {
        this.queryFileById(id);
      }
    });
  };

  queryFileById = (fileId) => {
    queryService({ fileId }).then((response) => {
      if (response.success && response.data.length > 0) {
        const fileInfo = this.convertResponseToFileInfo(response.data[0]);
        this.addFileToState(fileInfo);
      }
    });
  };

  convertResponseToFileInfo = (data) => ({
    name: data.fileName,
    uid: data.id,
    type: data.fileType,
    id: data.id,
    url: `/api/files/download?id=${data.id}`
  });

  addFileToState = (file) => {
    const { uploadedFiles, fileRecords } = this.state;
    if (!uploadedFiles.includes(file.id)) {
      this.setState({
        uploadedFiles: [...uploadedFiles, file.id],
        fileRecords: [...fileRecords, file]
      }, () => this.notifyParent());
    }
  };

  removeFileFromState = (fileToRemove) => {
    const { fileRecords } = this.state;
    const updatedRecords = fileRecords.filter((file) => file.id !== fileToRemove.id);
    this.setState({ fileRecords: updatedRecords }, () => this.notifyParent());
  };

  resetState = () => {
    this.isInitialValueEmpty = true;
    this.setState({ uploadedFiles: [], fileRecords: [] }, () => this.notifyParent());
  };

  notifyParent = () => {
    const { onChange } = this.props;
    const ids = this.state.uploadedFiles.join(',');
    onChange(ids);
  };

  handleUpload = ({ file }) => {
    const formData = new FormData();
    formData.append('file', file);

    uploadService(formData).then((response) => {
      if (response.success && response.data.length > 0) {
        const fileInfo = this.convertResponseToFileInfo(response.data[0]);
        this.addFileToState(fileInfo);
      } else {
        message.error('文件上传失败');
      }
    });
  };

  render() {
    const { fileRecords } = this.state;
    const { maxFiles = 1, buttonText = '点击上传' } = this.props;

    return (
      <Upload
        customRequest={(options) => this.handleUpload(options)}
        fileList={fileRecords}
        onRemove={(file) => this.removeFileFromState(file)}
        disabled={maxFiles <= fileRecords.length}
      >
        <Button>
          <span>{buttonText}</span>
        </Button>
      </Upload>
    );
  }
}

export default CustomFileUploader;

接下来,在表单中使用该自定义组件:

const TemplateFileItem = ({ data, form, style }) => {
  return (
    <Form.Item
      label="模板文件"
      labelCol={{ span: 5 }}
      wrapperCol={{ span: 15 }}
      style={style}
    >
      {form.getFieldDecorator('templateFileId', {
        rules: [{ required: false, message: '请选择文件' }],
        initialValue: data.templateFileId
      })(
        <CustomFileUploader 
          maxFiles={1} 
          placeholder="请选择文件" 
          autoComplete="off" 
        />
      )}
    </Form.Item>
  );
};

上述代码实现了将文件上传组件与表单字段绑定的功能,同时支持初始化值同步和动态更新。

标签: reactAntDesign

相关文章

可以按小时收费的VPS

很多 VPS 提供商都支持 按小时计费(hourly billing),想短期试用 / 临时搭建节点、测试网络、短期项目等场景非常合适。下面是当前最主流且靠谱的按小时 VPS 选项,分别按不同需求场景整理: 1. Vultr(全球节点,包括日本) 按小时计费 可选机房:东京 / 大阪 / 洛杉矶 / 法兰克福 / 伦敦 … 支持 PayPal(部分情况),但更常用信用卡/PayPal+卡价格参考$...

在 iPhone 上下载国外App

地区/国家限制App Store 会根据 Apple ID 的国家或地区限制应用下载。如果你的 Apple ID 绑定的是中国大陆,就可能无法下载 OpenAI 官方的 ChatGPT 应用,因为它在大陆 App Store 不上架。解决办法:换成美国、加拿大、香港等地区的 Apple ID。或者在现有 Apple ID 上更改地区。注册一个国外 Apple ID(推荐)比如注册 美国区 Appl...

Node.js 中的异步编程:回调与 Promise

Node.js 是一个基于 JavaScript 构建的单线程、非阻塞运行环境,它通过异步编程机制来高效处理多个操作。在执行如文件读取、API 请求或数据库查询等任务时,Node.js 不会等待这些操作完成,而是使用回调函数和 Promise 来避免阻塞主线程。 回调方式实现异步 那么当异步操作完成后,Node.js 如何知道接下来要做什么呢?这就要用到 回调函数(callback)。 回调本质上...

Selenium自动化测试入门指南

Selenium自动化测试入门指南

什么是自动化测试? 自动化测试是指利用软件工具自动执行测试用例,模拟用户操作,如打开网页、点击链接、输入文本等,并验证结果是否符合预期。 其主要优点包括: 大幅减少人工成本 测试速度快 可以在非工作时间运行 支持持续集成和交付 然而,它也存在一些局限性,例如开发成本较高、不适合快速变化的项目、依赖稳定的UI界面等。 自动化测试的应用条件 适合引入自动化测试的情况包括: 手动测试耗时且需要大量...

MariaDB Galera集群故障快速恢复指南

OpenStack控制节点采用三节点MariaDB Galera集群架构。当数据库集群因故障重启时,有时会出现Galera集群无法正常启动的问题。虽然有多种方法可以恢复数据库服务,但如何实现快速启动同时确保数据完整性呢? 通过分析日志发现,MariaDB Galera集群节点宕机时会在日志中输出以下信息: [Note] WSREP: 新集群视图:全局状态: 874d8e7e-5980-11e8-8...

Android 中 EventBus 的通信机制与实现原理深度解析

EventBus 核心设计思想 EventBus 是一个基于观察者模式的事件总线框架,广泛应用于 Android 平台以实现组件解耦。它通过中心化的消息分发机制,使不同层级、不同线程的对象能够以"发布-订阅"方式通信,避免了传统接口回调或广播带来的强依赖问题。 核心角色说明 事件(Event):任意 Java 对象,作为数据载体,如网络状态变更通知、用户登录信息等。 发布者(Publi...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。