react中,使用antd的Upload组件上传zip压缩包文件

需求

使用antd的Upload上传.zip压缩包文件

代码

javascript 复制代码
const [uploadLoaing, setUploadLoaing] = useState(false);

// 辅助函数:检查文件是否为zip格式
  function isZipFile(file: File): boolean {
    const fileType = file.type;
    return fileType === 'application/zip' || file.name.endsWith('.zip');
  }

const props= {
    name: 'file',
    multiple: false,
    action: `${envConfig.baseURL}/model/import`,   //上传的接口地址
    headers: {
      'X-Webtoken': getToken() || '',   //请求头携带token
    },
    accept: '.zip',
    showUploadList: false,
    onChange(info) {
      console.log('info=>', info);
      const { status } = info.file;
      if (status === 'uploading') {
        setUploadLoaing(true);
      }
      if (status === 'done') {
        if (info.file.response.code === 0) {
          message.success(`文件导入成功`);
          setUploadLoaing(false);
        } else {
          const errorMsg = info.file.response.data?.[0] || info.file.response.desc || '文件导入失败';
          message.error(errorMsg);
          setUploadLoaing(false);
        }
      } else if (status === 'error') {
        message.error(`文件导入失败`);
        setUploadLoaing(false);
      }
    },

    beforeUpload(file) {
      const isZip = isZipFile(file);
      const maxSize = 200 * 1024 * 1024;
      if (!isZip) {
        message.error('请上传一个压缩包文件。');
      } else if (file.size > maxSize) {
        message.error('文件大小不能超过200兆。');
      }

      return isZip && file.size <= maxSize;   //若返回false,则阻止上传行为
    },
};


<Upload {...props}>
    <Button loading={uploadLoaing}>上传</Button>
</Upload>
相关推荐
houhou14 分钟前
Monaco Editor 集成指南:从配置到优化
前端
hunterandroid17 分钟前
[Android 从零到一] Custom View 自定义绘制:从 onDraw 到完整交互
前端
李明卫杭州22 分钟前
Vue3 v-memo 指令详解:让你的列表渲染性能翻倍 🚀
前端
梨子同志33 分钟前
Monorepo
前端
lihaozecq35 分钟前
继 Web Coding Agent 后,我做了一个本地优先的桌面 AI Agent
前端·agent
用户2986985301442 分钟前
在 React 中使用 JavaScript 将 Excel 转换为 SVG
前端·javascript·react.js
CodingSpace1 小时前
ESLint
前端
Csvn1 小时前
异步错误捕获的六大陷阱:await 裹着 try-catch 就一定稳了吗?
前端
用户059540174461 小时前
向量库静默丢数据踩坑实录:Playwright 端到端测试让我排查了72小时
前端·css
星栈1 小时前
SPA 写累了?试试 LiveView:服务端管状态,前端不写 JS
前端·前端框架·elixir