ant-design/components/upload/demo/upload-manually.tsx
二货爱吃白萝卜 e7aa014c31
chore: Add type util (#46923)
* docs: init

* chore: all types

* docs: faq

* chore: fix lint
2024-01-11 15:55:58 +08:00

70 lines
1.8 KiB
TypeScript

import React, { useState } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Button, message, Upload } from 'antd';
import type { GetProp, UploadFile, UploadProps } from 'antd';
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
const App: React.FC = () => {
const [fileList, setFileList] = useState<UploadFile[]>([]);
const [uploading, setUploading] = useState(false);
const handleUpload = () => {
const formData = new FormData();
fileList.forEach((file) => {
formData.append('files[]', file as FileType);
});
setUploading(true);
// You can use any AJAX library you like
fetch('https://run.mocky.io/v3/435e224c-44fb-4773-9faf-380c5e6a2188', {
method: 'POST',
body: formData,
})
.then((res) => res.json())
.then(() => {
setFileList([]);
message.success('upload successfully.');
})
.catch(() => {
message.error('upload failed.');
})
.finally(() => {
setUploading(false);
});
};
const props: UploadProps = {
onRemove: (file) => {
const index = fileList.indexOf(file);
const newFileList = fileList.slice();
newFileList.splice(index, 1);
setFileList(newFileList);
},
beforeUpload: (file) => {
setFileList([...fileList, file]);
return false;
},
fileList,
};
return (
<>
<Upload {...props}>
<Button icon={<UploadOutlined />}>Select File</Button>
</Upload>
<Button
type="primary"
onClick={handleUpload}
disabled={fileList.length === 0}
loading={uploading}
style={{ marginTop: 16 }}
>
{uploading ? 'Uploading' : 'Start Upload'}
</Button>
</>
);
};
export default App;