React Antd Upload組件上傳多個文件實現(xiàn)方式
更新時間:2025年08月30日 10:55:48 作者:水果攤見
為實現(xiàn)多文件上傳,需使用beforeUpload和customRequest替代onChange以避免多次調用問題,并處理文件路徑以兼容Electron不同平臺
前言
實現(xiàn)需求:
上傳多個文件。其實就是獲取多個文件的絕對路徑交給后端接口去處理。
Upload組件
首先,這里不能調用Upload的onChange函數(shù),因為上傳中、完成、失敗都會調用這個函數(shù),在多個文件的情況下會出現(xiàn)多次調用問題。
改用beforeUpload和customRequest。
import React, { useRef, useState, useEffect } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd';
import { Button, Upload } from 'antd';
import { useTranslation } from 'react-i18next';
import Console from '../../../../util/Console';
import { UploadChangeParam } from 'antd/es/upload';
import { sendMsgToMain } from 'electron-prokit';
type Props = {
name?: string;
onChangeFilePath: (path: string | null | unknown, info?: UploadChangeParam<UploadFile<any>>) => void;
accept: Array<string>;
headers?: any;
progress?: any;
buttonTitle?: string;
rest?: UploadProps;
action?: string | ((file: any) => Promise<string>);
};
const FileMultiSelectButton: React.FC<Props> = ({
name,
onChangeFilePath,
accept,
headers,
progress = null,
buttonTitle,
action,
...rest
}) => {
const { t } = useTranslation();
const fileState: any = useRef();
const [uploadFiles, setUploadFiles] = useState<UploadFile[]>([]);
const updateFiles = (function () {
let fileList: UploadFile[] | null = null;
return function (list: UploadFile[], setState: React.Dispatch<React.SetStateAction<UploadFile[]>>) {
if (!fileList) {
fileList = list;
setState && setState(list);
}
return {
fileList,
reset() {
fileList = null;
}
};
};
})();
const beforeUpload = (_: any, fileList: UploadFile[]) => {
fileState.current = updateFiles(fileList, setUploadFiles);
return false;
}
const customRequest = () => {
if (uploadFiles.length > 0) {
const path = uploadFiles.map(item => (item as any).path);
// 這是electron的ipc處理函數(shù),在node中復制文件
sendMsgToMain({ key: 'fileMultiSelectPath', data: path }).then(filePath => {
if (typeof onChangeFilePath === 'function') {
onChangeFilePath(filePath);
} else {
Console.handleErrorMsg('onChangeFilePath is not a function');
}
});
} else {
Console.handleWarningMsg('no file uploaded');
}
}
useEffect(() => {
if (uploadFiles.length > 0) {
customRequest();
fileState.current.reset();
}
}, [uploadFiles]);
return (
<Upload
name={name || 'file'}
accept={accept.join(',')}
progress={progress}
showUploadList={false}
headers={headers}
action={action}
multiple={true}
beforeUpload={beforeUpload}
customRequest={customRequest}
{...rest}
>
<Button icon={<UploadOutlined />}> {buttonTitle || t('Select')} </Button>
</Upload>
);
};
export default FileMultiSelectButton;
在node中處理(不必須),這里主要因為electron需要兼容不同的平臺,需要處理文件路徑
function generateRandomString(length: number) {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
const fileSelectPath = (sourcePath: string) => {
return new Promise((resolve, reject) => {
const userDataPath = app.getPath('userData');
// 獲取用戶數(shù)據(jù)目錄,并在該目錄下創(chuàng)建文件夾,用于保存用戶數(shù)據(jù),需要判斷是否存在,如果存在則直接使用,否則創(chuàng)建,并返回該目錄,用于后續(xù)操作,并需要兼容跨平臺,比如windows和mac
// 拼接出 files 目錄的完整路徑
const filesDirPath = path.join(userDataPath, 'files');
fs.mkdir(filesDirPath, { recursive: true }, err => {
if (err) {
// 如果目錄創(chuàng)建失敗,返回錯誤信息
// 如果目錄創(chuàng)建失敗,處理錯誤
console.error('Failed to create files directory:', err);
}
// 生成一個隨機數(shù)
const randomBytes = generateRandomString(8); // 生成8字節(jié)的隨機數(shù)
// 獲取當前日期和時間
const date = new Date();
const formattedDate = date.toISOString().split('T')[0].replace(/-/g, ''); // 格式化為不含破折號的日期
const formattedTime = date.toTimeString().split(' ')[0].replace(/:/g, ''); // 格式化為不含冒號的時間
// 提取源文件名和擴展名
const { name, ext } = path.parse(sourcePath);
// 根據(jù)日期、時間和隨機數(shù)生成一個新的文件名
const newName = `${name}_${formattedDate}_${formattedTime}_${randomBytes}${ext}`;
// 構造目標路徑
const destinationPath = path.join(filesDirPath, newName);
// 使用fs模塊的copy方法復制文件
fs.copyFile(sourcePath, destinationPath, err => {
if (err) {
// 如果文件已存在或復制失敗,返回錯誤信息
reject(err);
} else {
// 復制成功,返回新的文件路徑
resolve(destinationPath);
}
});
});
});
};
export const fileMultiSelectPath = (sourcePath: Array<string>) => {
return Promise.all(sourcePath.map(async (sourcePath) => {
return await fileSelectPath(sourcePath);
}));
};
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
React-Hook中使用useEffect清除定時器的實現(xiàn)方法
這篇文章主要介紹了React-Hook中useEffect詳解(使用useEffect清除定時器),主要介紹了useEffect的功能以及使用方法,還有如何使用他清除定時器,需要的朋友可以參考下2022-11-11
React中的路由嵌套和手動實現(xiàn)路由跳轉的方式詳解
這篇文章主要介紹了React中的路由嵌套和手動實現(xiàn)路由跳轉的方式,手動路由的跳轉,主要是通過Link或者NavLink進行跳轉的,實際上我們也可以通JavaScript代碼進行跳轉,需要的朋友可以參考下2022-11-11
React Draggable插件如何實現(xiàn)拖拽功能
這篇文章主要介紹了React Draggable插件如何實現(xiàn)拖拽功能問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07
React Hooks: useEffect()調用了兩次問題分析
這篇文章主要為大家介紹了React Hooks: useEffect()調用了兩次問題分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11

