使用Antd的Upload组件对文件进行上传

Upload组件结合Form

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import React from 'react'
import { Upload, Button, Icon, Form } from 'antd';
const FormItem = Form.Item
class MyUpload extends React.Component {
state = {
fileList: [{
uid: -1,
name: 'xxx.png',
status: 'done',
url: 'http://www.baidu.com/xxx.png',
}],
}
handleChange = (info) => {
// file 正在上传的文件
// fileList 正在上传和已上传的文件
let { file, fileList } = info;
// 1. Limit the number of uploaded files
// Only to show two recent uploaded files, and old ones will be replaced by the new
fileList = fileList.slice(-2);
// 2. read from response and show file link
fileList = fileList.map((file) => {
// 对file进行处理,取所需的字段,使file看起来简洁
if (file.response) {
// Component will show file.url as link
file.url = file.response.url;
}
return file;
});
// 3. filter successfully uploaded files according to response from server
fileList = fileList.filter((file) => {
if (file.response) {
return file.response.status === 'success';
}
return true;
});
// 受控组件
// Upload控件onChange方法只会执行一次,且info.file.status一直为uploading
this.setState({ fileList });
}
render() {
const { getFieldDecorator } = this.props.form
const { fileList } = this.state
const uploadProps = {
action: '//jsonplaceholder.typicode.com/posts/',
listType: "picture",
multiple: true,
onRemove: () => {
if (canDelete) {
message.info('不可删除')
return false
}
return true
}
};
return (
<Form>
<FormItem>
{
getFieldDecorator('upload', {
rules: [{ required: true, message: 'upload file please!' }],
valuePropName: 'fileList', //子节点的值的属性,默认‘value’
getValueFromEvent: handleChange, //可以把 onChange 的参数转化为控件的值
initialValue: fileList
})(
<Upload {...uploadProps}>
<Button>
<Icon type="upload" /> upload
</Button>
</Upload>
)
}
</FormItem>
</Form>
);
}
}
export default Form.create()(MyUpload);
  • 受控组件
  • Upload控件onChange方法只会执行一次,且info.file.status一直为uploading 查看handleChange中this.setState({ fileList });
  • 如果需要向handleChange传入其他参数
    1
    2
    3
    getFieldDecorator('upload', {
    getValueFromEvent: (info) => handleChange(info, ect)
    })()