ant-design/components/upload/demo/upload-manually.md

85 lines
1.9 KiB
Markdown
Raw Normal View History

2017-07-14 15:00:14 +08:00
---
order: 7
title:
zh-CN: 手动上传
en-US: Upload manually
---
## zh-CN
`beforeUpload` 返回 `false` 后,手动上传文件。
## en-US
Upload files manually after `beforeUpload` returns `false`.
```tsx
import { UploadOutlined } from '@ant-design/icons';
2022-05-21 22:14:15 +08:00
import { Button, message, Upload } from 'antd';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
2022-05-21 22:14:15 +08:00
import React, { useState } from 'react';
2017-07-14 15:00:14 +08:00
const App: React.FC = () => {
const [fileList, setFileList] = useState<UploadFile[]>([]);
const [uploading, setUploading] = useState(false);
2017-07-14 15:00:14 +08:00
const handleUpload = () => {
2017-07-14 15:00:14 +08:00
const formData = new FormData();
2019-05-07 14:57:32 +08:00
fileList.forEach(file => {
formData.append('files[]', file.originFileObj as RcFile);
2017-07-14 15:00:14 +08:00
});
setUploading(true);
2017-07-14 15:00:14 +08:00
// You can use any AJAX library you like
fetch('https://www.mocky.io/v2/5cc8019d300000980a055e76', {
method: 'POST',
body: formData,
})
.then(res => res.json())
.then(() => {
setFileList([]);
2017-07-14 15:00:14 +08:00
message.success('upload successfully.');
})
.catch(() => {
message.error('upload failed.');
})
.finally(() => {
setUploading(false);
});
2019-05-07 14:57:32 +08:00
};
2017-07-14 15:00:14 +08:00
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,
};
2017-07-14 15:00:14 +08:00
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>
</>
);
};
2017-07-14 15:00:14 +08:00
export default App;
2019-05-07 14:57:32 +08:00
```