upload组件里面action就是调upload接口,获取图片url地址
setImg获取url,点击保存传到后台
action 上传头像方法
//上传头像 changeImg = info => { if (info.file.status === "uploading") { this.setState({ loading: true }); return; } if (info.file.status === "done") { let { userStore: { setImg } } = this.props; setImg(info.file.response.data.url); //根据实际后端接口数据结构获取数据 this.getBase64(info.file.originFileObj, imageUrl => this.setState({ imageUrl, loading: false }) ); } }; getBase64 = (img, callback) => { const reader = new FileReader(); reader.addEventListener("load", () => callback(reader.result)); reader.readAsDataURL(img); }; beforeUpload = file => { 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; };
render
<FormItem {...formItemLayout} label={'头像'}> {getFieldDecorator('avatar', { initialValue: avatar })( <Upload accept=".jpg, .jpeg, .png" listType="picture-card" showUploadList={false} action="/staffs/UploadFile.json" //后端提供的upload接口,返回url beforeUpload={this.beforeUpload} f onChange={this.changeImg} name="file" headers={{ Authorization: sessionStorage.authToken }} > {imageUrl ? <img src={imageUrl} alt="avatar" style={{ '100%' }} /> : uploadButton} </Upload> )} <span>{'支持JPG/GIF/PNG格式'}</span> </FormItem>