React+AntD文件上传并自定义上传逻辑

上传组件 DragClickUpload.tsx

import {CloudUploadOutlined} from '@ant-design/icons';
import type {UploadProps} from 'antd';
import {message, Upload} from 'antd';
import React, {useState} from 'react';
import axios from "axios";
const {Dragger} = Upload;
import Bus from "../../../utils/eventBus";
import KeyManServices from "src/services/keyMan";

const handleRequest = async (options: any) => {
    const { onSuccess, onError, file, onProgress } = options;
    const formData = new FormData();
    formData.append('file', file);
    formData.append('uploadVersionNo', sessionStorage.getItem('upload-version-no'));
    try {
        const response = await axios.post('/zdr/zdrinfo/importZdr', formData, {
            onUploadProgress: (progressEvent) => {
                const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            },
        });
        if (response.data.status === 200) {
            message.success('上传成功');
            Bus.emit('refresh-table-data')
        } else {
            message.success('上传失败');
        }
    } catch (error) {
        message.success('上传失败');
    }
}
const DragClickUpload = React.forwardRef((props, ref) => {
    const [fileList, setFileList] = useState([])
    const uploadAttr: UploadProps = {
        name: 'file',
        fileList,
        multiple: true,
        showUploadList: true,
        customRequest: handleRequest,
        onChange(info: any) {
            console.log('output-> info:::::: ', info)
            const {status} = info.file;
            console.log('output-> status::: ', status)
        },
        onDrop(e) {
            console.log('Dropped files', e.dataTransfer.files);
        },
    };


    React.useImperativeHandle(ref, () => ({
        uploadAttr,
        setFileList
    }));

    const onDownloadTemplate = (e: any) => {
        e.stopPropagation()
        window.open('/zdr/zdrinfo/exportTemplate')
    }
    return (
        <Dragger {...uploadAttr}>
            <main className="import-upload-box">
                <section className="left-icon">
                    <CloudUploadOutlined/>
                </section>
                <section className="right-desc-box">
                    <div className="desc-row">
                        <span>点击上传</span>
                        <span><i>/</i> 拖拽文件到此区域</span>
                        <span onClick={(e) => onDownloadTemplate(e)}>下载模板</span>
                    </div>
                    <div className="desc-row-p">
                        <p>支持excel文件(单个Excel最大100M)</p>
                    </div>
                </section>
            </main>
        </Dragger>
    )
})


export default DragClickUpload;

posted @ 2024-11-20 10:34  Felix_Openmind  阅读(8)  评论(0编辑  收藏  举报