react + pro-components + ts完成单文件上传和批量上传

上传部分使用的是antd中的Upload组件,具体如下:

GradingFilingReportUpload方法是后端已经做好文件流,前端只需要调用接口即可

单文件上传

javascript 复制代码
<Upload
    key={`upload_${record.id}`}
    showUploadList={false}
    accept=".xlsx"
    maxCount={1}
    customRequest={({ file }) => {
        const formData = new FormData();
        formData.append('id', record.id);
        formData.append('ins', file);
        GradingFilingReportUpload(formData).then(res => {
            if (res.state === 200) {
                message.success(res.message);
            } else {
                message.error('上传失败');
            }
        })
    }}
><a >上传</a></Upload>

多文件上传

页面组件

html 复制代码
<Upload
    showUploadList={false}
    multiple
    customRequest={({ file, onSuccess, onError }) => {
        handleRequestAllFile([file]).then(() => onSuccess && onSuccess('上传成功')).catch(() => onError)
    }}
>
    <a >批量上传</a>
</Upload>

js逻辑

javascript 复制代码
    const handleRequestAllFile = async (fileList: any[]) => {
        try {
            const formData = new FormData();
            fileList.forEach((file) => {
                formData.append('ins', file);
            })
            const res = await GradingFilingReportUpload(formData);
            if (res.state === 200) {
                message.success('文件上传成功');
            } else {
                message.error('文件上传失败');
            }
        } catch (e) {
            message.error('文件上传过程出错')
        }
    }

完整页面代码

javascript 复制代码
import { downLoad, downLoadStream } from '@/util/request';
import { ProTable } from '@ant-design/pro-components';
import { getTableColumns } from './colums'
import { useEffect, useRef, useState } from 'react';
import DeleteBtn from './components/DeleteBtn';
import { Button, Table, Upload, message } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import type { GradingFilingReportData, GradingFilingReportSelect } from '@/types/GradingFilingReport';
import { GradingFilingReportDataList, deleteDataById, GradingFilingReportUpload } from '@/service/GradingFilingReport'
import AddEditModal, { MODAL_TYPE } from './components/AddEditModal';
const GradingFilingReport = () => {
    const [columns, setColumns] = useState<ProColumns<GradingFilingReportData>[]>([]);
    const actionRef = useRef<ActionType>();
    const [SortOrderTest, setSortOrderTest] = useState<string>('');
    const [valueEnums, setValueEnums] = useState<GradingFilingReportSelect>({});
    // 获取表格数据
    const getData = async (filter: any) => {
        const params = { ...filter, offSet: filter.current, orderType: SortOrderTest };
        delete params.current;
        const { state, total, data } = (await GradingFilingReportDataList(params)) || {};
        if (state === 200) {
            return { data, success: true, total: total };
        } else {
            return { data: [] };
        }
    };
    // 下载文件
    const downLoadFileThis = async (item: any) => {
        let fileName = item.systemName + '.xlsx'
        let id = item.id
        let downloadParams = { id }
        let url = '/projectAcceptance/service/ratingFilingReportService/downloadReport/0'
        downLoad(url, downloadParams).then(res => {
            downLoadStream(res, fileName);
        }).catch((e) => {
            message.error('导出失败');
        }).finally(() => {
            console.log('完成');
        })
    }
    // 获取表格的表头数据
    const getTableConfig = async () => {
        const { columns, valueEnums } = await getTableColumns();
        setValueEnums(valueEnums);
        setColumns([
            ...columns,
            {
                title: '操作',
                valueType: 'option',
                key: 'option',
                fixed: 'right',
                width: 160,
                align: 'center',
                render: (text, record: any, index, action) => [
                    <AddEditModal
                        key={`edit_${record.id}`}
                        type={MODAL_TYPE.EDIT}
                        record={record}
                        valueEnums={valueEnums}
                        callback={() => {
                            action && action.reload();
                        }}
                    />,
                    <DeleteBtn<Array<any>>
                        key={`delete_${record.id}`}
                        params={record.id || ''}
                        method={deleteDataById}
                        callback={() => {
                            action && action.reload();
                        }}
                    />,
                    <Upload
                        key={`upload_${record.id}`}
                        showUploadList={false}
                        accept=".xlsx"
                        maxCount={1}
                        customRequest={({ file }) => {
                            const formData = new FormData();
                            formData.append('id', record.id);
                            formData.append('ins', file);
                            GradingFilingReportUpload(formData).then(res => {
                                if (res.state === 200) {
                                    message.success(res.message);
                                } else {
                                    message.error('上传失败');
                                }
                            })
                        }}
                    ><a >上传</a></Upload>
                    ,
                    <a key={`download_${record.id}`} onClick={() => downLoadFileThis(record)}>下载</a>
                ],
            },
        ]);
    }
    // 批量上传的方法
    const handleRequestAllFile = async (fileList: any[]) => {
        try {
            const formData = new FormData();
            fileList.forEach((file) => {
                formData.append('ins', file);
            })
            const res = await GradingFilingReportUpload(formData);
            if (res.state === 200) {
                message.success('文件上传成功');
            } else {
                message.error('文件上传失败');
            }
        } catch (e) {
            message.error('文件上传过程出错')
        }
    }
    // 批量上传的按钮
    const toolBarRender = (action: ActionType | undefined) => {
        return [
            <Upload
                showUploadList={false}
                multiple
                customRequest={({ file, onSuccess, onError }) => {
                    handleRequestAllFile([file]).then(() => onSuccess && onSuccess('上传成功')).catch(() => onError)
                }}
            >
                <a >批量上传</a>
            </Upload>
        ];
    };
    // 完成排序功能
    const handleChange = (pagination: any, filters: any, sorter: any) => {
        console.log(sorter, 'sorter');
        if (sorter.order !== undefined) {
            setSortOrderTest(sorter.order === 'descend' ? 'DESC' : 'ASC');
        }
    };
    // 初始化调用
    useEffect(() => {
        getTableConfig()
    }, [])
    return (
        <ProTable<GradingFilingReportData>
            rowKey="id"
            cardBordered
            actionRef={actionRef}
            request={getData}
            columns={columns}
            search={{
                labelWidth: 100,
            }}
            onChange={handleChange}
            toolBarRender={toolBarRender}
            scroll={{ x: 'max-content' }}
            rowSelection={{
                selections: [Table.SELECTION_ALL],
            }}
            tableAlertOptionRender={({ selectedRowKeys }) => {
                return (
                    <DeleteBtn<Array<any>>
                        content={
                            <Button type="link" icon={<DeleteOutlined />}>
                                {'批量删除'}
                            </Button>
                        }
                        method={deleteDataById}
                        params={selectedRowKeys}
                        callback={() => actionRef.current && actionRef.current.reload()}
                    />
                );
            }}
        />
    )
}
export default GradingFilingReport
相关推荐
程序员黄同学40 分钟前
Python 中如何创建多行字符串?
前端·python
anyup_前端梦工厂1 小时前
uni-app 认识条件编译,了解多端部署
前端·vue.js·uni-app
Fetters042 小时前
一篇快速上手 Axios,一个基于 Promise 的网络请求库(涉及原理实现)
前端·ajax·axios·promise
蒟蒻的贤2 小时前
vue11.22
开发语言·前端·javascript
爱上语文2 小时前
Axios案例练习
前端·javascript·css·html
河畔一角2 小时前
升级react@18.3.1后,把我坑惨了
前端·react.js·低代码
天天进步20152 小时前
Vue 3 + Vite:构建闪电般快速的开发环境
前端·javascript·vue.js
Dragon Wu2 小时前
前端框架 Redux tool RTK 总结
前端·javascript·前端框架
yqcoder2 小时前
reactflow 中 useStoreApi 模块作用
前端·javascript
williamdsy2 小时前
【vue】关于异步函数使用不当导致的template内容完全无法渲染的问题
前端·javascript·vue.js