javascript - let files = event.target.files; does not have a file - Stack Overflow

I have the following react ponent, but in the for statement, it never steps into the for loop, like fil

I have the following react ponent, but in the for statement, it never steps into the for loop, like files array is empty, so file is never sent to the server.

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';

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


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

  handleChangeTenantPassword(event){
    this.setState({TenantPassword: event.target.value});
  }

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

  handleSubmit(event){
    event.preventDefault();

    let data = new FormData();
    //Append files to form data
    let files = event.target.files;
    for (let i = 0; i < files.length; i++) {
      data.append("file", files[i], files[i].name);
    }

    //add other objects or params
    data.append("TenantId", this.state.TenantId);
    data.append("TenantUrl", this.state.TenantUrl);
    data.append("TenantPassword", this.state.TenantPassword);


    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 data = new FormData();
      //Append files to form data
      let files = e.target.files;
      for (let i = 0; i < files.length; i++) {
        data.append('content', files[i], files[i].name);
      }      
  }

  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.TenantPassword} onChange={this.handleChangeTenantPassword} />
                </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>
    );
  }
}

I have the following react ponent, but in the for statement, it never steps into the for loop, like files array is empty, so file is never sent to the server.

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';

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


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

  handleChangeTenantPassword(event){
    this.setState({TenantPassword: event.target.value});
  }

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

  handleSubmit(event){
    event.preventDefault();

    let data = new FormData();
    //Append files to form data
    let files = event.target.files;
    for (let i = 0; i < files.length; i++) {
      data.append("file", files[i], files[i].name);
    }

    //add other objects or params
    data.append("TenantId", this.state.TenantId);
    data.append("TenantUrl", this.state.TenantUrl);
    data.append("TenantPassword", this.state.TenantPassword);


    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 data = new FormData();
      //Append files to form data
      let files = e.target.files;
      for (let i = 0; i < files.length; i++) {
        data.append('content', files[i], files[i].name);
      }      
  }

  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.TenantPassword} onChange={this.handleChangeTenantPassword} />
                </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>
    );
  }
}
Share Improve this question asked Jul 19, 2018 at 18:44 Luis ValenciaLuis Valencia 34.1k99 gold badges311 silver badges532 bronze badges 2
  • Would it not be better to put the files in state first, and then use these files from the state in your handleSubmit method, and put them in the formData before the request? – Tholle Commented Jul 19, 2018 at 18:48
  • no idea how to do that – Luis Valencia Commented Jul 19, 2018 at 18:58
Add a ment  | 

1 Answer 1

Reset to default 2

I have modified the required functions should work now.

constructor(props) {
    super(props);
    this.state = {TenantId: '', TenantUrl: '', TenantPassword: '', selectedFiles: null };
    this.handleChangeTenantUrl = this.handleChangeTenantUrl.bind(this);
    this.handleChangeTenantPassword = this.handleChangeTenantPassword.bind(this);
    this.handleChangeTenantId= this.handleChangeTenantId.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  };

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

handleSubmit(event){
    event.preventDefault();

    let data = new FormData();
    //Append files to form data
    let files = this.state.files;
    for (let i = 0; i < files.length; i++) {
      data.append("file", files[i], files[i].name);
    }

    //add other objects or params
    data.append("TenantId", this.state.TenantId);
    data.append("TenantUrl", this.state.TenantUrl);
    data.append("TenantPassword", this.state.TenantPassword);


    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);
      });
  }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745357420a4624202.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信