Ant Design表单文件上传:多文件上传与进度展示

Ant Design表单文件上传:多文件上传与进度展示

【免费下载链接】ant-design An enterprise-class UI design language and React UI library 【免费下载链接】ant-design 项目地址: https://gitcode.com/gh_mirrors/antde/ant-design

概述

在企业级应用开发中,文件上传功能是常见需求,尤其在表单场景下需要支持多文件选择、上传进度展示和状态管理。Ant Design提供了功能完备的Upload组件,通过简单配置即可实现专业的文件上传体验。本文将从实际应用场景出发,详细介绍如何使用Ant Design实现多文件上传与进度展示功能。

基础配置与多文件上传

Ant Design的Upload组件位于components/upload/Upload.tsx,通过设置multiple属性即可开启多文件上传模式。以下是基础配置示例:

import { UploadOutlined } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd';
import { Button, Upload } from 'antd';

const App: React.FC = () => {
  const [fileList, setFileList] = useState<UploadFile[]>([
    {
      uid: '-1',
      name: '示例文件.png',
      status: 'done',
      url: 'http://example.com/file.png',
    },
  ]);

  const handleChange: UploadProps['onChange'] = (info) => {
    // 限制最多上传2个文件
    const newFileList = info.fileList.slice(-2);
    setFileList(newFileList);
  };

  const props: UploadProps = {
    action: 'https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload',
    onChange: handleChange,
    multiple: true, // 开启多文件上传
    listType: 'text', // 文件列表展示形式
  };

  return (
    <Upload {...props} fileList={fileList}>
      <Button icon={<UploadOutlined />}>选择文件</Button>
    </Upload>
  );
};

上述代码来自components/upload/demo/fileList.tsx,通过设置multiple: true允许用户同时选择多个文件,fileList状态用于管理已上传/待上传文件列表。

进度展示实现原理

上传进度展示是通过监听上传过程中的进度事件实现的。在components/upload/Upload.tsx中,Upload组件提供了onProgress回调函数:

const onProgress = (e: { percent: number }, file: RcFile) => {
  // 更新文件进度
  const targetItem = file2Obj(file);
  targetItem.status = 'uploading';
  targetItem.percent = e.percent;
  
  const nextFileList = updateFileList(targetItem, mergedFileList);
  onInternalChange(targetItem, nextFileList, e);
};

要在UI中显示进度条,只需在Upload组件中配置progress属性:

<Upload
  {...props}
  progress={{
    strokeWidth: 3,
    showInfo: true, // 显示百分比文字
  }}
>
  <Button icon={<UploadOutlined />}>上传文件</Button>
</Upload>

高级UI样式配置

Ant Design提供了多种文件列表展示样式,通过listType属性控制:

  1. 文本列表 (listType="text"):默认样式,简洁文本展示
  2. 图片卡片 (listType="picture-card"):适合图片类文件展示
  3. 圆形图片 (listType="picture-circle"):圆形缩略图展示

图片卡片样式示例(components/upload/demo/picture-card.tsx):

<Upload
  action="https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload"
  listType="picture-card"
  fileList={fileList}
  onPreview={handlePreview}
  onChange={handleChange}
>
  {fileList.length < 4 && '上传图片'}
</Upload>

错误处理与状态管理

Upload组件提供了完善的状态管理机制,文件状态包括:

  • uploading:上传中
  • done:上传完成
  • error:上传失败
  • removed:已移除

错误处理实现(components/upload/Upload.tsx):

const onError = (error: Error, response: any, file: RcFile) => {
  const targetItem = file2Obj(file);
  targetItem.error = error;
  targetItem.response = response;
  targetItem.status = 'error';
  
  const nextFileList = updateFileList(targetItem, mergedFileList);
  onInternalChange(targetItem, nextFileList);
};

完整示例:多文件上传组件

结合上述功能,以下是一个完整的多文件上传组件实现,包含进度展示、文件预览和错误处理:

import React, { useState } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Image, Button, Upload, message } from 'antd';
import type { UploadFile, UploadProps } from 'antd';

const MultiFileUpload: React.FC = () => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');

  // 预览图片
  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await new Promise<string>((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj as Blob);
        reader.onload = () => resolve(reader.result as string);
      });
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewVisible(true);
  };

  // 处理上传状态变化
  const handleChange: UploadProps['onChange'] = ({ file, fileList }) => {
    if (file.status === 'error') {
      message.error(`${file.name} 上传失败,请重试`);
    }
    setFileList(fileList);
  };

  const uploadProps: UploadProps = {
    action: 'https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload',
    listType: 'picture-card',
    fileList,
    onPreview: handlePreview,
    onChange: handleChange,
    multiple: true,
    progress: {
      strokeWidth: 3,
      showInfo: true,
    },
    maxCount: 5, // 限制最多上传5个文件
  };

  return (
    <>
      <Upload {...uploadProps}>
        <div>
          <UploadOutlined />
          <div style={{ marginTop: 8 }}>上传文件</div>
        </div>
      </Upload>
      
      {/* 图片预览模态框 */}
      <Image
        preview={{ 
          visible: previewVisible, 
          onVisibleChange: setPreviewVisible 
        }}
        src={previewImage}
      />
    </>
  );
};

export default MultiFileUpload;

总结与最佳实践

  1. 性能优化:通过beforeUpload限制文件大小和类型,减少无效上传
  2. 用户体验:始终显示上传进度,提供清晰的成功/失败反馈
  3. 安全考虑:服务端必须验证文件类型和内容,防止恶意文件上传
  4. 兼容性:对于大文件上传,考虑实现分片上传功能

更多高级用法可参考官方文档和示例代码:

通过合理配置Ant Design的Upload组件,可以轻松实现企业级的文件上传功能,满足各种复杂业务场景需求。

【免费下载链接】ant-design An enterprise-class UI design language and React UI library 【免费下载链接】ant-design 项目地址: https://gitcode.com/gh_mirrors/antde/ant-design

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

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

抵扣说明:

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

余额充值