React实战之Ant Design—Upload上传_附件上传

原文链接: http://www.cnblogs.com/Yu-Shuai/p/10870427.html

React实战之Ant Design—Upload上传_附件上传

Upload组件大家都在官方文档中看过了,但写的时候还是会遇到许多问题,一些新手看了文档后感觉无从下手,本文过多的简绍就不说了,直接看代码和注释,直接用就行

我直接放在form表单中,因为实战中单个附件上传很少几,乎都在form表单中加入一个附件上传所以为了更好的应用,我直接就放在form表单中应用

import React, { PureComponent } from 'react';
import {Form, Button, Icon,Upload} from 'antd';

const FormItem = Form.Item;
@Form.create()
class xxx extends PureComponent {
    state = {
        fileList: [],//存放上传信息:比如路径、文件名
        imgList: [],//存放回显信息:修改时的路径、文件名
    };

    //form表单提交事件
    handleSubmit = e => {
        const { dispatch, form } = this.props;
        e.preventDefault();
        form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                const { imgList } = this.state
                values.imgList = JSON.stringify(imgList);
                console.log('values', values);
            }
        });
    };

    //上传事件
    onChange = ({ fileList }) => {
        console.log('file', fileList);
        let imgList = [];
        fileList.map(function (item, key) {
            if (item.response && item.response.success) {
          console.log('item.response',item.response);
                imgList.push({ url: item.response.url, Name: item.response.name });//这的参数具体看上传成功后返回的值,打印的item.response
            } else {
                //回显
                if (item.url) {
                    //拼接'http:// 如果路径可以直接使用不需要拼接
                    imgList.push({ url: item.url.replace('http://', ""), Name: item.name });
                }
            }
        });
        this.setState({ fileList, imgList });
    } 
    render() {//const {form: { getFieldDecorator, getFieldValue }} = this.props;
     const { fileList } = this.state
        const props = {
            name: 'UploadFile',//name得看接口需求,name与接口需要的name一致
            action: 'http://.......',//接口路径
            data: {  },//接口需要的参数,无参数可以不写
            multiple: true,//支持多个文件
            showUploadList: true,//展示文件列表
        }

        return (
        <Form onSubmit={this.handleSubmit}><FormItem label="附件">
            <Upload {...props}
              fileList={fileList}
              onChange={this.onChange}
                    >
                      <Button>
                <Icon type="upload" /> 上传附件
              </Button>
                      </Upload>,
                   </FormItem>
           <FormItem >
            <Button type="primary" htmlType="submit" >
              提交
            </Button>
            </FormItem>
         </Form>
        );
    }
export default xxx;

  

代码可以用于新增功能和编辑功能,如有问题欢迎联系!不到之处多多指教

转载于:https://www.cnblogs.com/Yu-Shuai/p/10870427.html

猜你喜欢

转载自blog.csdn.net/weixin_30279671/article/details/95007315