feat: upload files

This commit is contained in:
xion 2024-10-12 19:21:07 +08:00
parent 3eaa94eb46
commit ab6c4340f5
5 changed files with 136 additions and 21 deletions

View File

@ -1,14 +1,16 @@
import { Form, Input } from 'antd';
import { Button, Form, Input } from 'antd';
import { useUserStore } from '../store';
import { useEffect } from 'react';
import { useEffect, useRef, useState } from 'react';
import { useShallow } from 'zustand/react/shallow';
import { isObjectNull } from '@/utils/is-null';
import { useLayoutStore } from '@/modules/layout/store';
import { AvatarUpload } from '../module/AvatarUpload';
import { UploadOutlined } from '@ant-design/icons';
import PandaPNG from '@/assets/panda.png';
import { FileUpload } from '../module/FileUpload';
export const Profile = () => {
const [form] = Form.useForm();
const ref = useRef<any>(null);
const userStore = useUserStore(
useShallow((state) => {
return {
@ -17,18 +19,20 @@ export const Profile = () => {
formData: state.formData,
updateData: state.updateData,
setFormData: state.setFormData,
updateSelf: state.updateSelf,
};
}),
);
const [avatar, setAvatar] = useState<string>('');
const layoutStore = useLayoutStore(
useShallow((state) => {
return {
me: state.me,
setMe: state.setMe,
};
}),
);
const avatar = layoutStore.me?.avatar;
// const avatar = layoutStore.me?.avatar;
useEffect(() => {
const fromData = layoutStore.me;
if (isObjectNull(fromData)) {
@ -36,8 +40,20 @@ export const Profile = () => {
} else {
form.setFieldsValue(fromData);
}
console.log('fromData', fromData);
setAvatar(fromData.avatar || '');
}, [layoutStore.me]);
const onChange = (path: string) => {
let url = '/resources/' + path;
console.log('path', url);
form.setFieldsValue({ avatar: url });
setAvatar(url + '?t=' + new Date().getTime());
};
const onFinish = async (values) => {
const newMe = await userStore.updateSelf(values);
if (newMe) {
layoutStore.setMe(newMe);
}
};
return (
<div className='w-full h-full bg-gray-200 p-4'>
<div className='border shadow-lg p-4 bg-white rounded-lg'>
@ -51,23 +67,24 @@ export const Profile = () => {
</div>
<Form
form={form}
onFinish={onFinish}
labelCol={{
span: 4,
}}>
<Form.Item label='Name' name='username'>
<Input className='w-full border rounded-lg p-2' disabled />
</Form.Item>
<Form.Item label='id' name='id' hidden>
<Input />
</Form.Item>
<Form.Item label='avatar' name='Avatar'>
<Form.Item label='Avatar' name='avatar'>
<Input
addonAfter={
<UploadOutlined
onClick={() => {
console.log('upload');
}}
/>
<div>
<UploadOutlined
onClick={() => {
ref.current?.open?.();
}}
/>
<FileUpload ref={ref} onChange={onChange} />
</div>
}
/>
</Form.Item>
@ -75,13 +92,9 @@ export const Profile = () => {
<Input.TextArea rows={4} />
</Form.Item>
<Form.Item label=' ' colon={false}>
<button
className='bg-blue-500 text-white px-4 py-2 rounded-lg'
onClick={() => {
userStore.updateData(form.getFieldsValue());
}}>
<Button className='' htmlType='submit'>
</button>
</Button>
</Form.Item>
</Form>
</div>

View File

@ -51,14 +51,19 @@ export const AvatarUpload = () => {
console.log('file', file);
return '';
};
const customAction = (file) => {
console.log('file', file);
}
return (
<Flex gap='middle' wrap>
<Upload
name='avatar'
listType='picture-circle'
className='avatar-uploader'
multiple={false}
showUploadList={false}
action={onAciton}
customRequest={customAction}
beforeUpload={beforeUpload}
onChange={handleChange}>
{imageUrl ? <img src={imageUrl} alt='avatar' style={{ width: '100%' }} /> : uploadButton}

View File

@ -0,0 +1,80 @@
import { message } from 'antd';
import { useImperativeHandle, useRef, forwardRef } from 'react';
import type { GetProp, UploadProps } from 'antd';
type FileTypeOrg = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
export type FileType = {
name: string;
size: number;
lastModified: number;
webkitRelativePath: string; // 包含name
};
const beforeUpload = (file: FileTypeOrg) => {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('You can only upload JPG/PNG file!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('Image must smaller than 2MB!');
}
return isJpgOrPng && isLt2M;
};
type Props = {
onChange: (path: string) => void;
};
export const FileUpload = forwardRef<any, Props>((props, ref) => {
const inputRef = useRef<HTMLInputElement | null>(null);
const onChange = async (e) => {
if (!beforeUpload(e.target.files[0])) {
return;
}
console.log(e.target.files);
const file = e.target.files[0];
const endType = file.name.split('.').pop();
const formData = new FormData();
formData.append('file', file, `avatar.${endType}`); // 保留文件夹路径
const res = await fetch('/api/upload', {
method: 'POST',
body: formData, //
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token'),
},
}).then((res) => res.json());
if (res?.code === 200) {
console.log('res', res);
//
const [file] = res.data;
const { path } = file || {};
props?.onChange?.(path);
//
} else {
message.error(res.message || 'Request failed');
}
// 清理之前上传的文件
e.target.value = '';
};
// 把ref 传递到上层
useImperativeHandle(ref, () => {
return {
open: () => {
inputRef.current?.click();
},
};
});
return (
<div>
<input
style={{
display: 'none',
}}
ref={inputRef}
accept='image/*'
type='file'
multiple={false}
onChange={onChange}
/>
</div>
);
});

View File

@ -11,6 +11,7 @@ type UserStore = {
list: any[];
getList: () => Promise<void>;
updateData: (data: any) => Promise<void>;
updateSelf: (data: any) => Promise<any>;
deleteData: (id: string) => Promise<void>;
};
export const useUserStore = create<UserStore>((set, get) => {
@ -51,6 +52,22 @@ export const useUserStore = create<UserStore>((set, get) => {
message.error(res.message || 'Request failed');
}
},
updateSelf: async (data) => {
const loaded = message.loading('Action in progress..', 0);
const res = await query.post({
path: 'user',
key: 'updateSelf',
data,
});
loaded();
if (res.code === 200) {
message.success('Success');
set({ formData: res.data });
return res.data;
} else {
message.error(res.message || 'Request failed');
}
},
deleteData: async (id) => {
const { getList } = get();
const res = await query.post({

2
theme

@ -1 +1 @@
Subproject commit bff92667f4bed0f8d15ed5e6fe1c75ce22480bd2
Subproject commit c4e0ec2a5322503a4755d9b42d8f628d76ba0b28