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

106 lines
2.1 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`.
````jsx
2018-11-28 15:00:03 +08:00
import {
Upload, Button, Icon, message,
} from 'antd';
2017-07-14 15:00:14 +08:00
import reqwest from 'reqwest';
class Demo extends React.Component {
state = {
fileList: [],
uploading: false,
}
handleUpload = () => {
const { fileList } = this.state;
const formData = new FormData();
fileList.forEach((file) => {
formData.append('files[]', file);
});
this.setState({
uploading: true,
});
// You can use any AJAX library you like
reqwest({
url: '//jsonplaceholder.typicode.com/posts/',
method: 'post',
processData: false,
data: formData,
success: () => {
this.setState({
fileList: [],
uploading: false,
});
message.success('upload successfully.');
},
error: () => {
this.setState({
uploading: false,
});
message.error('upload failed.');
},
});
}
render() {
const { uploading, fileList } = this.state;
2017-07-14 15:00:14 +08:00
const props = {
onRemove: (file) => {
this.setState((state) => {
const index = state.fileList.indexOf(file);
const newFileList = state.fileList.slice();
2017-07-14 15:00:14 +08:00
newFileList.splice(index, 1);
return {
fileList: newFileList,
};
});
},
beforeUpload: (file) => {
this.setState(state => ({
fileList: [...state.fileList, file],
2017-07-14 15:00:14 +08:00
}));
return false;
},
fileList,
2017-07-14 15:00:14 +08:00
};
return (
<div>
<Upload {...props}>
<Button>
<Icon type="upload" /> Select File
</Button>
</Upload>
<Button
type="primary"
onClick={this.handleUpload}
disabled={fileList.length === 0}
2017-07-14 15:00:14 +08:00
loading={uploading}
style={{ marginTop: 16 }}
2017-07-14 15:00:14 +08:00
>
{uploading ? 'Uploading' : 'Start Upload' }
</Button>
</div>
);
}
}
ReactDOM.render(<Demo />, mountNode);
````