A
A
aznhautroalvyl2019-03-13 08:15:24
HTML
aznhautroalvyl, 2019-03-13 08:15:24

Uploading multiple files to a server?

Task: upload several files to the server (backend on Node.js)
Added a form for uploading files and a handler for it:

class InputFile extends Component {
  constructor(props) {
    super(props);
    this.state = {     
      selectedFile: null,
      // selectedFile: [],
      filesList: []     
    };
  }

  uploadChosenFile(selectedFile, fileName) {
    this.setState({
      selectedFile,
      filesList: fileName
    });
  }

  handleUploadFile(event) {
    const list = this.state.filesList;

    list.push(event.target.files[0].name);
    this.uploadChosenFile(event.target.files, list);
  }

  render() {
    return (
      <div>
        <input id='file' name='file'
          type='file' formEncType='multipart/form-data' onChange={this.handleUploadFile}
          multiple
        />
        <div>
          {this.state.filesList.map(item => {
            return (<a className='edit__form-group-link' href='#' key={'1'}>{item}</a>);
          })}
        </div>
      </div>
    );
  }
}

After clicking on the submit button, the function is called from the same component:
uploadFilesToServer(idEvent) {
    const data = new FormData();

    this.state.selectedFile.map(el => {
      data.append('file', el, el.name);
      axios.post(`${Config.baseUrl}/upload/${idEvent}`, data);
    });
  }

As a result, only the last file of all the selected ones was sent to the server.
I tried to make an array from this.state.selectedFile and transfer one file and it, but I got a 500 error in the console. Tell me, please, where is the error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gleip, 2019-03-14
@3ongleip

Here is the line
data.append('file', el, el.name);
Should be replaced with
data.append('file[]', el, el.name);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question