Pass parameters (including an image) to PHP with Axios using formData

1

I created a React component to be my custom input button:

getFormData(){
    var formData = new FormData();
    var imagefile = document.querySelector('#btn_file_logo');
    formData.append("image", imagefile.files[0]);
    return formData;
}

render() {
    return (
        <div>
            <div className="logo_input" onClick={() => this.abirInputFile()}><i className="fa fa-upload"> </i> {this.props.texto}</div>
            <input type="file" className="form-control-file" id="btn_file_logo" name="btn_file_logo"  />
      </div>
    );
}

But I'm having trouble using formData . The getFormData() function should return formData to another component, which will get it and add append to the rest of the parameters that will be sent to the server (I use PHP with the Slim Framework on the server side) p>

cadastrar(){
    this.refs.load.openLoad();

    var formData = this.refs.input_logo.getFormData();
    formData.append('nome',this.state.nome);
    formData.append('cnpj',this.state.cnpj);

    axios.post(config.urlBase + 'adicionar_empresa', {empresa:formData}).then(res => {
      if(res.data.status){
        this.refs.sucesso.openSucesso(2000);
        this.refs.load.closeLoad();
        this.limparCampos();
      }else{
        this.refs.erro.openErro(3000);
        this.refs.load.closeLoad();
      }
    })
}

The problem is that the server arrives empty parameters.

    
asked by anonymous 06.06.2018 / 16:01

1 answer

0

I was able to solve

axios.post(config.urlBase + 'adicionar_empresa', {empresa:formData})

I was passing the parameter in JSON, the correct one is

axios.post(config.urlBase + 'adicionar_empresa', formData)
    
06.06.2018 / 19:12