koa_system: 🔥🔥🔥Koa2 + React商城项目前端-React + Antd前端-Vue2 + Element-plus后端-Koa2 + Sequelizehttps://gitee.com/ah-ah-bao/koa_system
import React from 'react';
import { Upload, Button, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { API_URL, getToken } from '../../utils/common';
import type { UploadProps } from 'antd';
import type { UploadPropsType } from './index.type';
const UploadComponent: React.FC<UploadPropsType> = ({
maxCount = 1,
showUploadList = true,
uploadUrl = '/upload',
typename = 'file',
onUploadSuccess,
}) => {
const props: UploadProps = {
name:typename,
action: API_URL + uploadUrl,
headers: {
Authorization: getToken() || 'defaultTokenValue',
},
onChange(info) {
if (info.file.status !== 'uploading') {
console.log(info.file, info.fileList);
}
switch (info.file.status) {
case 'done':
message.success(`${info.file.name} file uploaded successfully`);
if (onUploadSuccess && info.file.response && info.file.response.data && info.file.response.data.url) {
onUploadSuccess(info.file.response.data.url); // 调用回调函数
}
if (onUploadSuccess && info.file.response && info.file.response.data && info.file.response.data.image) {
onUploadSuccess(info.file.response.data.image); // 调用回调函数
}
break;
case 'error':
message.error(`${info.file.name} file upload failed.`);
break;
default:
break;
}
},
};
return (
<Upload {...props} maxCount={maxCount} showUploadList={showUploadList}>
<Button icon={<UploadOutlined />}>上传</Button>
</Upload>
);
};
export default UploadComponent;
export interface UploadPropsType {
maxCount?:number;
showUploadList?:boolean;
uploadUrl?:string;
typename?:string;
onUploadSuccess?: (url: string) => void; // 添加回调函数属性
}
import { UploadComponent } from "./UploadComponent";
<UploadComponent
maxCount={1}
showUploadList={false}
uploadUrl="/goods/upload"
typename="file"
onUploadSuccess={handleUploadSuccess} // 传递回调函数
/>;
// maxCount: 最大上传数量
// showUploadList: 是否显示上传列表
// uploadUrl: 上传地址
// typename: 上传文件类型
// onUploadSuccess: 上传成功回调函数 =>>使用方式
const handleUploadSuccess = (url: string) => {
setGoodsimg(url); //设置这个返回的路径
};