Antd 封装一个 Form Upload 组件

2,957 阅读1分钟

背景

Upload 文件上传在后台项目中可谓是最常见的功能了,今天封装一个 Form Upload 组件。

一、在 Form 表单中使用 Upload

1、封装上传组件 MyUpload ,在 Form 表单中使用:

import React, { useState } from "react";
import { Button, Upload, Form } from "antd";
import { UploadOutlined } from "@ant-design/icons";

const MyUpload = ({ name }) => {
    const [fileList, setFileList] = useState([]);
    const normFile = (e) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };

    const beforeUpload = (file) => {
        setFileList([file]);
        return false;
    };

    const onRemove = () => {
        setFileList([]);
    };

    return (
        <Form.Item
            name={name}
            valuePropName="fileList"
            getValueFromEvent={normFile}
        >
            <Upload
                fileList={fileList}
                beforeUpload={beforeUpload}
                onRemove={onRemove}
            >
                <Button icon={<UploadOutlined />}>Click to Upload</Button>
            </Upload>
         </Form.Item>
    );
};

export default MyUpload

2、在 Form 中使用 MyUpload 组件:

import React, { useEffect, useState } from 'react'
import { Form } from 'antd'
import MyUpload from './MyUpload'

const MyForm = () => {
    const [form] = Form.useForm()

    const onFinish = ({ file }) => {
        const formData = {
            file: file.[0].originFileObj // 获取 File 类型文件
        }
        // 这里写表单提交逻辑...
    }

    return (
        <Form form={form} onFinish={onFinish}>
            <MyUpload name="file" />
        </Form>
    )
}

export default MyForm

二、普通场景使用 Upload

通常情况下,我们直接个 Upload 的 action 属性赋值为上传地址,就可以实现简单的上传功能,废话不多说,直接上 demo 。

import React from "react";
import ReactDOM from "react-dom";
import { Button, Upload, message } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import "antd/dist/antd.css";
import "./index.css";

const props = {
    name: "file",
    action: "https://www.mocky.io/v2/5cc8019d300000980a055e76",
    headers: {
        authorization: "authorization-text"
    },
    onChange(info) {
        if (info.file.status !== "uploading") {
            console.log(info.file, info.fileList);
        }
        if (info.file.status === "done") { // 上传成功
            message.success(`${info.file.name} file uploaded successfully`);
        } else if (info.file.status === "error") { // 上传失败
            message.error(`${info.file.name} file upload failed.`);
        }
    }
};

ReactDOM.render(
    <div className="App">
        <Upload {...props}>
            <Button icon={<UploadOutlined />}>Click to Upload</Button>
        </Upload>
    </div>,
    document.getElementById("root")
);

通过 onChange 方法获取上传结果,成功和失败分别根据业务进行处理即可。如图,上传成功和失败的日志如下: image.png