import React, { useState, useContext, useEffect, useRef } from "react"; import { Upload as AntdUpload, UploadFile, message, Button } from "antd"; import { RcFile } from "antd/es/upload"; import { UploadOutlined } from "@ant-design/icons"; import OSS from "ali-oss"; import dayjs from "dayjs"; import { LocaleContext } from "../../locale/LocaleProvider"; import Units from "../../units"; const fileNameRegex = /([^\/?#]+)(?:[?#].*)?$/; export interface UploadProps { disabled?: boolean; value?: string; onChange?: (data: string) => void; id?: string; max?: number; fieldConfig?: { serverKey?: string; }; } interface OssConfig { accessKeyId: string; accessKeySecret: string; bucket: string; endpoint: string; protocol: string; } const Index: React.FC = (props) => { const { onChange, disabled, value, id, fieldConfig: { serverKey }, max: maxCount = 1 } = props; const { translate } = useContext(LocaleContext); const [fileList, setFileList] = useState([]); const clientRef = useRef(null); const [ossConfig, setOssConfig] = useState(); useEffect(() => { if (serverKey) { const { accessKeyId, accessKeySecret, bucket, endpoint, protocol } = Units.getExtendServers(serverKey) || {}; setOssConfig({ accessKeyId, accessKeySecret, bucket, endpoint, protocol }); if (accessKeyId && accessKeySecret && bucket && endpoint) { clientRef.current = new OSS({ accessKeyId, accessKeySecret, bucket, endpoint }); } } }, [serverKey]); // 处理value,上传多文件时,value使用逗号隔开 const handleValue = (val: string) => { const urls = val.split(","); const fileList: UploadFile[] = urls.map(url => { const temUrl = url.startsWith("http") ? url : `${ossConfig.protocol || "http"}://${ossConfig.bucket}.${ossConfig.endpoint}/${url}`; const name = temUrl.match(fileNameRegex)?.[1]; return { uid: temUrl, name: decodeURIComponent(name || ""), status: 'done', url: temUrl } }); setFileList(fileList); } useEffect(() => { if (ossConfig && value) { handleValue(value); } }, [value, ossConfig]) // 自定义上传 const customRequest = async ({ file, onProgress, onSuccess, onError }: any) => { try { const programCode = Units.programCode(); const fileName = `/${programCode}/${dayjs().format("YYYY-MM-DD")}/${file.name}`; // 上传文件到 OSS const result = await clientRef.current.put(fileName, file, { progress: (p) => { onProgress({ percent: p * 100 }); }, }); onSuccess(result, file); // 返回文件URL return { url: result.url, name: file.name, status: 'done', }; } catch (error) { onError(error); console.error(error); } }; const beforeUpload = async (file: RcFile) => { if (file.size > 200 * 1024 * 1024) { message.error(translate("${超过200M限制 不允许上传~}"), 5); return false; } if (!clientRef.current) { message.error(translate("${请配置OSS服务}")); return false; } return true; } const handleChange = async (info) => { switch (info.file.status) { case "done": message.success(`${info.file.name} ${translate("${上传成功}")}`); const url = info.file.response.url; const pathName = new URL(url).pathname.slice(1); onChange(value ? `${value},${pathName}` : pathName); break; case "removed": onChange(fileList.filter(item => item.uid !== info.file.uid).map(item => item.url.startsWith("http") ? new URL(item.url).pathname.slice(1) : item.url).join(",")); break; case "error": message.error(`${info.file.name} ${translate("${上传异常}")}`); break; default: break; } setFileList(info.fileList); }; return ( {fileList && fileList.length >= maxCount ? ( "" ) : ( )} ) }; export default Index;