简体   繁体   中英

file upload in react. not able to understand issue

Hi I Need to send one input filed and one file to server using react. I am using class component. My below code is not working properly. could you please check the same?

在此处输入图像描述

Below is my code.

import React from 'react';
import axios from 'axios';

class FileUpload extends React.Component {
  constructor() {
    super();
    this.state = {
      selectedFile: '',
      countryCode: '',
      responseArray: [],
    };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleInput = this.handleInput.bind(this);
  }

  handleInputChange(event) {
    this.setState({
      selectedFile: event.target.files[0],
      responseArray: [],
    });
  }

  handleInput(event) {
    this.setState({
      countryCode: event.target.value,
    });
  }

  handleSubmit(e) {
    e.preventDefault();
    if (!this.state.selectedFile) {
      alert('Please select The file');
      return false;
    }
    if (!this.state.countryCode) {
      alert('Please select The Country Code');
      return false;
    }
    const data = new FormData();

    for (let i = 0; i < this.state.selectedFile.length; i++) {
      data.append('file[]', this.state.selectedFile[i]);
    }
    data.append('countryCode', this.state.countryCode);
    alert(data.file || data.countryCode);

    let url = process.env.API_URL;

    axios.post(url, data, {}).then(
      (res) => {
        this.setState({ responseArray: res.data });
        this.resetFile();
      },
      (error) => {
        alert(error);
      }
    );
  }

  resetFile() {
    document.getElementsByName('file')[0].value = null;
  }

  render() {
    return (
      <form>
        <div className="row">
          <div className="col-md-12">
            <h1>Translation File Upload</h1>

            <div className="form-row">
              <div className="form-group col-md-8">
                <label>Please enter the country code</label>
                <input
                  type="text"
                  value={this.state.countryCode}
                  onChange={this.handleInput}
                  required
                />
              </div>
            </div>

            <div className="form-row">
              <div className="form-group col-md-8">
                <label>Select File :</label>
                <input
                  type="file"
                  className="form-control"
                  multiple
                  name="file"
                  onChange={this.handleInputChange}
                  required
                />
              </div>
            </div>
            <br />
            <div className="form-row">
              <div className="col-md-6">
                <button onClick={this.handleSubmit.bind(this)}>Upload </button>
              </div>
            </div>
            <br />
          </div>
        </div>
      </form>
    );
  }
}

export default FileUpload;

handleSubmit is not getting called after used enters the value. before that if user does not enter it gives validation error. I dont know what is the msitake?

you have an issue here:

  handleInputChange(event) {
    this.setState({
      selectedFile: event.target.files,
      countryCode: '',
      responseArray: [],
    });
  }

whenever you add a file, you set countryCode to '' and then you get catch by

if (!this.state.countryCode) {
  alert('Please enter country code!');
  return false;
}

You should do two changes to make it work

  handleInputChange(event) {
    this.setState({
      ...this.state,
      selectedFile: event.target.files,
      responseArray: [],
    });
  }

and

<div className="form-group col-md-8">
    <label>Please enter the country code</label>
    <input
        type="text"
        value={this.state.value}
        name="countryCode"
        onChange={(e) => { this.setState({...this.state, countryCode: e.target.value}) }}
        required
    />
</div>

setState() merges provided values. You don't have to pass entire state every time. f

setState(stateChange[, callback]) performs a shallow merge of stateChange into the new state. ref


working code on codepen :

class FileUpload extends React.Component {
  constructor() {
    super();
    this.state = {
      selectedFile: '',
      countryCode: '',
      responseArray: [],
    };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleInput = this.handleInput.bind(this);
  }

  handleInputChange(event) {
    this.setState({
      selectedFile: event.target.files[0],
      responseArray: [],
    });
  }

  handleInput(event) {
    this.setState({
      countryCode: event.target.value,
    });
  }

  handleSubmit(e) {
    e.preventDefault();
    if (!this.state.selectedFile) {
      alert('Please select The file');
      return false;
    }
    if (!this.state.countryCode) {
      alert('Please select The Country Code');
      return false;
    }
    const data = new FormData();

    for (let i = 0; i < this.state.selectedFile.length; i++) {
      data.append('file[]', this.state.selectedFile[i]);
    }
    data.append('countryCode', this.state.countryCode);
    
    alert('all good sending: '+this.state.countryCode + ' = ' + this.state.selectedFile);

    let url = process.env.API_URL;

    
  }

  resetFile() {
    document.getElementsByName('file')[0].value = null;
  }

  render() {
    return (
      <form>
        <div className="row">
          <div className="col-md-12">
            <h1>Translation File Upload</h1>

            <div className="form-row">
              <div className="form-group col-md-8">
                <label>Please enter the country code</label>
                <input
                  type="text"
                  value={this.state.countryCode}
                  onChange={this.handleInput}
                  required
                />
              </div>
            </div>

            <div className="form-row">
              <div className="form-group col-md-8">
                <label>Select File :</label>
                <input
                  type="file"
                  className="form-control"
                  multiple
                  name="file"
                  onChange={this.handleInputChange}
                  required
                />
              </div>
            </div>
            <br />
            <div className="form-row">
              <div className="col-md-6">
                <button onClick={this.handleSubmit.bind(this)}>Upload </button>
              </div>
            </div>
            <br />
          </div>
        </div>
      </form>
    );
  }
}



ReactDOM.render(
  <FileUpload />,
  document.getElementById('root')
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM