React實戰之Ant Design—Upload上傳_附件上傳


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;

  

代碼可以用於新增功能和編輯功能,如有問題歡迎聯系!不到之處多多指教


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM