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

Asked

Viewed 589 times

1

I created an 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 a hard time using formData. The function getFormData() must return the formData to another component, which will pick it up and add with append the rest of the parameters that will be sent to the server (I use PHP with Slim Framework on the server-side):

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 on the server arrive empty parameters.

inserir a descrição da imagem aqui

1 answer

0


I managed to solve

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

was passing the parameter in JSON, the correct is so

axios.post(config.urlBase + 'adicionar_empresa', formData)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.