antd upload action 不写(前端解析内容)

 

在使用Ant Design的Upload组件时,如果不提供action属性,那么文件的上传处理需要通过customRequest属性来自定义实现。

以下是一个不使用action属性,而是通过customRequest实现文件上传的例子:

 

import React from 'react';
import { Upload, message, Button } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
 
function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
}
 
function customRequest(option) {
  const { onSuccess, onError, file, onProgress } = option;
 
  // 自定义上传处理逻辑,例如使用fetch或者XMLHttpRequest
  const formData = new FormData();
  formData.append('file', file);
 
  // 模拟上传
  setTimeout(() => {
    // 模拟成功的响应
    onSuccess("success");
 
    // 模拟错误的响应
    // onError("error");
 
    // 模拟上传进度
    // onProgress({ percent: 50 });
  }, 1000);
}
 
const Demo = () => (
  <Upload
    name="file"
    onRemove={file => {
      console.log(file);
      return true;
    }}
    beforeUpload={beforeUpload}
    customRequest={customRequest}
  >
    <Button icon={<UploadOutlined />}>Click to Upload</Button>
  </Upload>
);
 
export default Demo;

 

自己的例子:

<Form.Item
          name="csv"
          label="csv文件"
          rules={[{ required: true, message: '请上传csv文件!' }]}
          valuePropName="fileList"
          getValueFromEvent={normFile}
          extra="如果上传多个文件,以第一个为准"
        >
          <Upload name="content" beforeUpload={beforeUpload} listType="text">
            <Button icon={<UploadOutlined />}>点击上传</Button>
          </Upload>
        </Form.Item>

去掉了也是OK的

<Upload name="content" action="/upload.do" ....中的action="/upload.do"。
 
踩了一个坑,必须这么写。直接写空方法是不行的。

 

 解决方法:调用onSuccess事件,解决loading一直加载的问题。

 
我的最终写法:
customRequest={(option: any)=>{ option.onSuccess() }}

 

 

posted @ 2024-05-13 14:54  走走停停走走  Views(101)  Comments(0Edit  收藏  举报