【问题标题】:file upload in react. not able to understand issue文件上传反应。无法理解问题
【发布时间】:2022-01-12 08:49:31
【问题描述】:

您好,我需要使用 react 向服务器发送一个输入文件和一个文件。我正在使用类组件。我的以下代码无法正常工作。你能检查一下吗?

下面是我的代码。

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 在 used 输入值后没有被调用。在此之前,如果用户不输入它会给出验证错误。我不知道msitake是什么?

【问题讨论】:

  • 您的最新代码似乎运行良好。 https://codepen.io/onkarruikar/pen/eYGXKaq
  • Onkar 非常感谢你。你救了我。如果您可以将此链接放在答案中,我可以标记它。它也会帮助其他人。

标签: javascript reactjs user-interface file-upload react-redux


【解决方案1】:

setState() 合并提供的值。您不必每次都通过整个状态。 f

setState(stateChange[, callback]) 将 stateChange 浅合并到新状态。 ref


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

【讨论】:

【解决方案2】:

你有问题:

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

每当你添加一个文件时,你将 countryCode 设置为 '' 然后你就会被捕获

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

您应该进行两项更改以使其正常工作

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

<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() 合并提供的值。您不必每次都通过整个状态。 ref "...执行 stateChange 到新状态的浅合并,"
猜你喜欢
  • 2011-08-09
  • 2022-01-22
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-21
  • 2015-06-05
相关资源
最近更新 更多