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

Ant Design Upload组件:上传后隐藏文件(无论成败)并保留进度条

Ant Design Upload 实现「上传时显示进度,完成后自动隐藏」方案

核心思路

不要直接覆盖整个fileList,而是通过动态维护fileList状态,结合Upload的回调函数跟踪每个文件的上传状态,只保留「正在上传」的文件在列表中,上传完成(成功/失败)后立即移除。

具体实现代码

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

const UploadDemo = () => {
  const [fileList, setFileList] = useState([]);

  // 处理文件添加:保留新选中的文件到列表
  const handleChange = ({ fileList: newFileList }) => {
    setFileList(newFileList);
  };

  // 更新上传进度:精准更新对应文件的进度值
  const handleProgress = (percent, file) => {
    setFileList(prev => 
      prev.map(item => 
        item.uid === file.uid ? { ...item, percent } : item
      )
    );
  };

  // 上传成功:移除文件+提示
  const handleSuccess = (res, file) => {
    setFileList(prev => prev.filter(item => item.uid !== file.uid));
    message.success(`${file.name} 上传成功`);
  };

  // 上传失败:移除文件+提示
  const handleError = (err, file) => {
    setFileList(prev => prev.filter(item => item.uid !== file.uid));
    message.error(`${file.name} 上传失败`);
  };

  return (
    <Upload
      action="/your-upload-api" // 替换为你的实际上传接口
      fileList={fileList}
      onChange={handleChange}
      onProgress={handleProgress}
      onSuccess={handleSuccess}
      onError={handleError}
      // 自定义渲染:只显示正在上传的文件
      itemRender={(originNode, file) => {
        return file.status === 'uploading' ? originNode : null;
      }}
    >
      <Button icon={<UploadOutlined />}>选择文件上传</Button>
    </Upload>
  );
};

export default UploadDemo;

关键说明

  • 之前操作fileList看不到进度的原因:直接替换整个fileList会丢失Ant Design Upload内部对文件进度的跟踪,这里通过map更新单个文件的percent属性,既保留了进度状态,又能实时渲染进度条。
  • itemRender是双重保险:即使状态更新有延迟,也能确保非上传中的文件不会显示在列表里。
  • 上传完成后通过filter移除对应文件,列表始终只显示正在上传的文件,完全匹配需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 16:36:11