最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use the upload control from ant design, to get a reference of the file - Stack Overflow

programmeradmin3浏览0评论

I have the following ponent and it works perfect.

import React, { Component } from 'react';
import { Row, Col } from 'antd';
import PageHeader from '../../ponents/utility/pageHeader';
import Box from '../../ponents/utility/box';
import LayoutWrapper from '../../ponents/utility/layoutWrapper.js';
import ContentHolder from '../../ponents/utility/contentHolder';
import basicStyle from '../../settings/basicStyle';
import IntlMessages from '../../ponents/utility/intlMessages';
import { adalApiFetch } from '../../adalConfig';
import RegisterTenantForm from './registertenantform';

export default class extends Component {
  constructor(props) {
    super(props);
    this.state = {TenantId: '', TenantUrl: '', CertificatePassword: '' };
    this.handleChangeTenantUrl = this.handleChangeTenantUrl.bind(this);
    this.handleChangeCertificatePassword = this.handleChangeCertificatePassword.bind(this);
    this.handleChangeTenantId= this.handleChangeTenantId.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  };


  handleChangeTenantUrl(event){
    this.setState({TenantUrl: event.target.value});
  }

  handleChangeCertificatePassword(event){
    this.setState({CertificatePassword: event.target.value});
  }

  handleChangeTenantId(event){
    this.setState({TenantId: event.target.value});
  }

  handleSubmit(event){
    event.preventDefault();

    let data = new FormData();
    //Append files to form data
    data.append("model", JSON.stringify({ "TenantId": this.state.TenantId, "TenantUrl": this.state.TenantUrl, "CertificatePassword": this.state.CertificatePassword }));
    //data.append("model", {"TenantId": this.state.TenantId, "TenantUrl": this.state.TenantUrl, "TenantPassword": this.state.TenantPassword });

    let files = this.state.selectedFiles;
    for (let i = 0; i < files.length; i++) {
      data.append("file", files[i], files[i].name);
    }

    const options = {
      method: 'put',
      body: data,
      config: {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
    };

    adalApiFetch(fetch, "/Tenant", options)
      .then(response => response.json())
      .then(responseJson => {
        if (!this.isCancelled) {
          this.setState({ data: responseJson });
        }
      })
      .catch(error => {
        console.error(error);
      });
  }


  upload(e){
    let files = e.target.files;
    this.setState({ 'selectedFiles': files });
}

  render(){
    const { data } = this.state;
    const { rowStyle, colStyle, gutter } = basicStyle;

    return (
      <div>
        <LayoutWrapper>
        <PageHeader>{<IntlMessages id="pageTitles.TenantAdministration" />}</PageHeader>
        <Row style={rowStyle} gutter={gutter} justify="start">
          <Col md={12} sm={12} xs={24} style={colStyle}>
            <Box
              title={<IntlMessages id="pageTitles.TenantAdministration" />}
              subtitle={<IntlMessages id="pageTitles.TenantAdministration" />}
            >
              <ContentHolder>

              <form onSubmit={this.handleSubmit}>
                <label>
                  TenantId:
                  <input type="text" value={this.state.TenantId} onChange={this.handleChangeTenantId} />
                </label>
                <label>
                  TenantUrl:
                  <input type="text" value={this.state.TenantUrl} onChange={this.handleChangeTenantUrl} />
                </label>
                <label>
                  TenantPassword:
                  <input type="text" value={this.state.CertificatePassword} onChange={this.handleChangeCertificatePassword} />
                </label>
                <label>
                  Certificate:
                  <input onChange = { e => this.upload(e) } type = "file" id = "files" ref = { file => this.fileUpload } />
                </label>             
              <input type="submit" value="Submit" />
              </form>
              </ContentHolder>
            </Box>
          </Col>
        </Row>
      </LayoutWrapper>
      </div>
    );
  }
}

Now, I need a nice design, I am using antd form ponents, and from the design point of view, everything is looking nice.

However, I am having a problem with handlesubmit, because e.target.files is undefined.

How can I use the upload control to put the file on the state when the control changes?

My work so far, problem is in e.target.files

import React, { Component } from 'react';
import { Input, Upload , Icon} from 'antd';
import Form from '../../ponents/uielements/form';
import Checkbox from '../../ponents/uielements/checkbox';
import Button from '../../ponents/uielements/button';
import Notification from '../../ponents/notification';
import { adalApiFetch } from '../../adalConfig';

const FormItem = Form.Item;

class RegisterTenantForm extends Component {
    constructor(props) {
        super(props);
        this.state = {TenantId: '', TenantUrl: '', CertificatePassword: '' };
        this.handleChangeTenantUrl = this.handleChangeTenantUrl.bind(this);
        this.handleChangeCertificatePassword = this.handleChangeCertificatePassword.bind(this);
        this.handleChangeTenantId= this.handleChangeTenantId.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    };

    handleChangeTenantUrl(event){
        this.setState({TenantUrl: event.target.value});
    }

    handleChangeCertificatePassword(event){
        this.setState({CertificatePassword: event.target.value});
    }

    handleChangeTenantId(event){
        this.setState({TenantId: event.target.value});
    }

    handleupload(e){
        let files = e.target.files;
        this.setState({ 'selectedFiles': files });
    }

    state = {
            confirmDirty: false,
    };

    handleSubmit(e){
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                /*Notification(
                'success',
                'Received values of form',
                JSON.stringify(values)
                );*/

                let data = new FormData();
                //Append files to form data
                data.append("model", JSON.stringify({ "TenantId": this.state.TenantId, "TenantUrl": this.state.TenantUrl, "CertificatePassword": this.state.CertificatePassword }));
                //data.append("model", {"TenantId": this.state.TenantId, "TenantUrl": this.state.TenantUrl, "TenantPassword": this.state.TenantPassword });

                let files = this.state.selectedFiles;
                for (let i = 0; i < files.length; i++) {
                  data.append("file", files[i], files[i].name);
                }

                const options = {
                  method: 'put',
                  body: data,
                  config: {
                    headers: {
                      'Content-Type': 'multipart/form-data'
                    }
                  }
                };

                adalApiFetch(fetch, "/Tenant", options)
                  .then(response => response.json())
                  .then(responseJson => {
                    if (!this.isCancelled) {
                      this.setState({ data: responseJson });
                    }
                  })
                  .catch(error => {
                    console.error(error);
                });
            }
        });      
    }



    render() {
        const { getFieldDecorator } = this.props.form;

        const formItemLayout = {
        labelCol: {
            xs: { span: 24 },
            sm: { span: 6 },
        },
        wrapperCol: {
            xs: { span: 24 },
            sm: { span: 14 },
        },
        };
        const tailFormItemLayout = {
        wrapperCol: {
            xs: {
            span: 24,
            offset: 0,
            },
            sm: {
            span: 14,
            offset: 6,
            },
        },
        };
        return (
            <Form onSubmit={this.handleSubmit}>
                <FormItem {...formItemLayout} label="Tenant Id" hasFeedback>
                {getFieldDecorator('tenantid', {
                    rules: [
                    {
                        required: true,
                        message: 'Please input your tenant id',
                    },
                    ],
                })(<Input name="tenantid" id="tenantid" onChange={this.handleChangeTenantId}/>)}
                </FormItem>
                <FormItem {...formItemLayout} label="Certificate Password" hasFeedback>
                {getFieldDecorator('certificatepassword', {
                    rules: [
                    {
                        required: true,
                        message: 'Please input your password!',
                    }
                    ],
                })(<Input type="certificatepassword" onChange={this.handleChangeCertificatePassword}/>)}
                </FormItem>
                <FormItem {...formItemLayout} label="Tenant admin url" hasFeedback>
                {getFieldDecorator('tenantadminurl', {
                    rules: [
                    {
                        required: true,
                        message: 'Please input your tenant admin url!',
                    }
                    ],
                })(<Input type="tenantadminurl" onChange={this.handleChangeTenantUrl} />)}
                </FormItem>
                <FormItem {...tailFormItemLayout}>
                    <Upload accept=".png" onChange={this.handleupload}>
                        <Button>
                            <Icon type="upload" /> Click to Upload
                        </Button>
                    </Upload>
                    <Button type="primary" htmlType="submit">
                        Register tenant
                    </Button>
                </FormItem>
            </Form>
        );
    }
}

const WrappedRegisterTenantForm = Form.create()(RegisterTenantForm);
export default WrappedRegisterTenantForm;

Documentation, which is not clear for me: /ponents/upload/

I have the following ponent and it works perfect.

import React, { Component } from 'react';
import { Row, Col } from 'antd';
import PageHeader from '../../ponents/utility/pageHeader';
import Box from '../../ponents/utility/box';
import LayoutWrapper from '../../ponents/utility/layoutWrapper.js';
import ContentHolder from '../../ponents/utility/contentHolder';
import basicStyle from '../../settings/basicStyle';
import IntlMessages from '../../ponents/utility/intlMessages';
import { adalApiFetch } from '../../adalConfig';
import RegisterTenantForm from './registertenantform';

export default class extends Component {
  constructor(props) {
    super(props);
    this.state = {TenantId: '', TenantUrl: '', CertificatePassword: '' };
    this.handleChangeTenantUrl = this.handleChangeTenantUrl.bind(this);
    this.handleChangeCertificatePassword = this.handleChangeCertificatePassword.bind(this);
    this.handleChangeTenantId= this.handleChangeTenantId.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  };


  handleChangeTenantUrl(event){
    this.setState({TenantUrl: event.target.value});
  }

  handleChangeCertificatePassword(event){
    this.setState({CertificatePassword: event.target.value});
  }

  handleChangeTenantId(event){
    this.setState({TenantId: event.target.value});
  }

  handleSubmit(event){
    event.preventDefault();

    let data = new FormData();
    //Append files to form data
    data.append("model", JSON.stringify({ "TenantId": this.state.TenantId, "TenantUrl": this.state.TenantUrl, "CertificatePassword": this.state.CertificatePassword }));
    //data.append("model", {"TenantId": this.state.TenantId, "TenantUrl": this.state.TenantUrl, "TenantPassword": this.state.TenantPassword });

    let files = this.state.selectedFiles;
    for (let i = 0; i < files.length; i++) {
      data.append("file", files[i], files[i].name);
    }

    const options = {
      method: 'put',
      body: data,
      config: {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
    };

    adalApiFetch(fetch, "/Tenant", options)
      .then(response => response.json())
      .then(responseJson => {
        if (!this.isCancelled) {
          this.setState({ data: responseJson });
        }
      })
      .catch(error => {
        console.error(error);
      });
  }


  upload(e){
    let files = e.target.files;
    this.setState({ 'selectedFiles': files });
}

  render(){
    const { data } = this.state;
    const { rowStyle, colStyle, gutter } = basicStyle;

    return (
      <div>
        <LayoutWrapper>
        <PageHeader>{<IntlMessages id="pageTitles.TenantAdministration" />}</PageHeader>
        <Row style={rowStyle} gutter={gutter} justify="start">
          <Col md={12} sm={12} xs={24} style={colStyle}>
            <Box
              title={<IntlMessages id="pageTitles.TenantAdministration" />}
              subtitle={<IntlMessages id="pageTitles.TenantAdministration" />}
            >
              <ContentHolder>

              <form onSubmit={this.handleSubmit}>
                <label>
                  TenantId:
                  <input type="text" value={this.state.TenantId} onChange={this.handleChangeTenantId} />
                </label>
                <label>
                  TenantUrl:
                  <input type="text" value={this.state.TenantUrl} onChange={this.handleChangeTenantUrl} />
                </label>
                <label>
                  TenantPassword:
                  <input type="text" value={this.state.CertificatePassword} onChange={this.handleChangeCertificatePassword} />
                </label>
                <label>
                  Certificate:
                  <input onChange = { e => this.upload(e) } type = "file" id = "files" ref = { file => this.fileUpload } />
                </label>             
              <input type="submit" value="Submit" />
              </form>
              </ContentHolder>
            </Box>
          </Col>
        </Row>
      </LayoutWrapper>
      </div>
    );
  }
}

Now, I need a nice design, I am using antd form ponents, and from the design point of view, everything is looking nice.

However, I am having a problem with handlesubmit, because e.target.files is undefined.

How can I use the upload control to put the file on the state when the control changes?

My work so far, problem is in e.target.files

import React, { Component } from 'react';
import { Input, Upload , Icon} from 'antd';
import Form from '../../ponents/uielements/form';
import Checkbox from '../../ponents/uielements/checkbox';
import Button from '../../ponents/uielements/button';
import Notification from '../../ponents/notification';
import { adalApiFetch } from '../../adalConfig';

const FormItem = Form.Item;

class RegisterTenantForm extends Component {
    constructor(props) {
        super(props);
        this.state = {TenantId: '', TenantUrl: '', CertificatePassword: '' };
        this.handleChangeTenantUrl = this.handleChangeTenantUrl.bind(this);
        this.handleChangeCertificatePassword = this.handleChangeCertificatePassword.bind(this);
        this.handleChangeTenantId= this.handleChangeTenantId.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    };

    handleChangeTenantUrl(event){
        this.setState({TenantUrl: event.target.value});
    }

    handleChangeCertificatePassword(event){
        this.setState({CertificatePassword: event.target.value});
    }

    handleChangeTenantId(event){
        this.setState({TenantId: event.target.value});
    }

    handleupload(e){
        let files = e.target.files;
        this.setState({ 'selectedFiles': files });
    }

    state = {
            confirmDirty: false,
    };

    handleSubmit(e){
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                /*Notification(
                'success',
                'Received values of form',
                JSON.stringify(values)
                );*/

                let data = new FormData();
                //Append files to form data
                data.append("model", JSON.stringify({ "TenantId": this.state.TenantId, "TenantUrl": this.state.TenantUrl, "CertificatePassword": this.state.CertificatePassword }));
                //data.append("model", {"TenantId": this.state.TenantId, "TenantUrl": this.state.TenantUrl, "TenantPassword": this.state.TenantPassword });

                let files = this.state.selectedFiles;
                for (let i = 0; i < files.length; i++) {
                  data.append("file", files[i], files[i].name);
                }

                const options = {
                  method: 'put',
                  body: data,
                  config: {
                    headers: {
                      'Content-Type': 'multipart/form-data'
                    }
                  }
                };

                adalApiFetch(fetch, "/Tenant", options)
                  .then(response => response.json())
                  .then(responseJson => {
                    if (!this.isCancelled) {
                      this.setState({ data: responseJson });
                    }
                  })
                  .catch(error => {
                    console.error(error);
                });
            }
        });      
    }



    render() {
        const { getFieldDecorator } = this.props.form;

        const formItemLayout = {
        labelCol: {
            xs: { span: 24 },
            sm: { span: 6 },
        },
        wrapperCol: {
            xs: { span: 24 },
            sm: { span: 14 },
        },
        };
        const tailFormItemLayout = {
        wrapperCol: {
            xs: {
            span: 24,
            offset: 0,
            },
            sm: {
            span: 14,
            offset: 6,
            },
        },
        };
        return (
            <Form onSubmit={this.handleSubmit}>
                <FormItem {...formItemLayout} label="Tenant Id" hasFeedback>
                {getFieldDecorator('tenantid', {
                    rules: [
                    {
                        required: true,
                        message: 'Please input your tenant id',
                    },
                    ],
                })(<Input name="tenantid" id="tenantid" onChange={this.handleChangeTenantId}/>)}
                </FormItem>
                <FormItem {...formItemLayout} label="Certificate Password" hasFeedback>
                {getFieldDecorator('certificatepassword', {
                    rules: [
                    {
                        required: true,
                        message: 'Please input your password!',
                    }
                    ],
                })(<Input type="certificatepassword" onChange={this.handleChangeCertificatePassword}/>)}
                </FormItem>
                <FormItem {...formItemLayout} label="Tenant admin url" hasFeedback>
                {getFieldDecorator('tenantadminurl', {
                    rules: [
                    {
                        required: true,
                        message: 'Please input your tenant admin url!',
                    }
                    ],
                })(<Input type="tenantadminurl" onChange={this.handleChangeTenantUrl} />)}
                </FormItem>
                <FormItem {...tailFormItemLayout}>
                    <Upload accept=".png" onChange={this.handleupload}>
                        <Button>
                            <Icon type="upload" /> Click to Upload
                        </Button>
                    </Upload>
                    <Button type="primary" htmlType="submit">
                        Register tenant
                    </Button>
                </FormItem>
            </Form>
        );
    }
}

const WrappedRegisterTenantForm = Form.create()(RegisterTenantForm);
export default WrappedRegisterTenantForm;

Documentation, which is not clear for me: https://ant.design/ponents/upload/

Share Improve this question asked Jul 24, 2018 at 7:33 Luis ValenciaLuis Valencia 34k99 gold badges309 silver badges532 bronze badges 1
  • Just as a note: to get the original file data for processing, its in a field file.originFileObj in handler onChange in <Upload/> – robertdavid Commented Mar 24, 2020 at 22:39
Add a ment  | 

4 Answers 4

Reset to default 4

Accordingly to documentation it seems that instead of trying to retrieve files list from e.target

handleupload(e) {
  let files = e.target.files;
  this.setState({ 'selectedFiles': files });
}

you should use antd's API and write something like next:

handleupload(info) {
  this.setState({ 'selectedFiles': info.fileList });
}

Also please pay attention to checking of files uploading statuses (info.file.status) and consider examples which make Upload ponent controlled.

I prefer beforeUpload. It accepts two args file and fileList, and if it returns false, then upload skipped :

handleupload(file, fileList){
    this.setState({ 'selectedFiles': fileList });
}
...
<Upload beforeUpload={this.handleupload} ... />

Ant Design Upload ponent is designed for backend upload/process ; what you are doing is frontend upload/process; so use beforeUpload -works great

const frontendUpload=(file,fileList)=>{
   // parseTheFile (file);   
   fileList.forEach(f=>parseTheFile(f))
   
}

Return (
   <div>
   <Upload beforeUpload={(file, fileList)=>{frontendUpload(file,fileList)}}>
      <Button icon={<UploadOutlined />}>Click to Upload</Button>
   </Upload>
   </div>
)

you can use the maxCount props that es with the upload ponent to set limit to files uploaded

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论