Difference between Formdata and form

Asked

Viewed 320 times

0

These days I was trying to upload data contained in a form. I used Node and React stack-like.

The form contained the following fields: product, description, cost, quantity, image(file type).

I used the encType="Multipart/form-data" on my form, since it was dealing with sending files to the server, but it was a mistake.

I researched about the Formdata and I used it in my code, so the data went up.

My Doubt is: what the difference between using the Formdata and the tag form? ***bold text

Document React

 async Cadastrar(e){
    e.preventDefault();
    const dt = new FormData();
    dt.append('produto',this.state.produto);
    dt.append('descricao',this.state.descricao);
    dt.append('custo',this.state.custo);
    dt.append('quantidade',this.state.quantidade);
    dt.append('imagem',this.state.imagem);

    try{
        const response = await api.post('/upload',dt);  
    }catch(e){
        return console.log("Oops.. houve um erro! "+e);
    }
}


render(){
    return(
        <div>
            <form onSubmit={this.Cadastrar} encType="multipart/form-data">
                <h1>Cadastrar Produto</h1>
                <h2>Preencha os campos para inserir um novo produto</h2>

                <input type="text" name="produto" placeholder="Informe o título do produto ex: Cookie, Café"
                 required
                 value={this.state.produto}
                 onChange={ (e)=>{ this.setState({ produto:e.target.value })} }
                 />
                <textarea name="descricao" rows="6" placeholder="Faça uma pequena descrição do produto ex: Bolo de nozes com nutella"
                 value={this.state.descricao}
                 onChange={ (e)=>{ this.setState({ descricao: e.target.value })} }
                 />
                <CurrencyInput name="custo" decimalSeparator = "," thousandSeparator = "."
                 required
                 value={this.state.custo}
                 onChange={this.Validate} // Chama função para validar que o campo traga apenas números, vírgula e ponto.
                 />
                <input type="number" name="quantidade" placeholder="Quantidade de produtos ex: 2,3" min={1}
                 required
                 value={this.state.quantidade}
                 onChange={ (e)=>{ this.setState({ quantidade: e.target.value })} }
                 />
                <input type="file" name="imagem"

                 onChange={ (e)=>{ 
                     const img = e.target.files[0];
                    this.setState({ imagem: img })
                        }
                    }
                 />
  • You could give an example of how you used Formdata and how the service consumed expects to receive the information?

  • I created a function called Register(e){ } - and every time I click on the input type="Submit" my form and submitted with its data. Within the Register function I created a const data = new Formdata( ) and there below the constant I put data.append('file',file).. and so I did for the other fields. Finally I still used inside my function Register, I used my api(Next) to consume the Node data.

1 answer

0

Actually there is no difference,the tag form sends your data in form-data format

ex: "name=username=16"

And the new instance of the "Formdata()" object takes the data you add through the "append" and formats it to "form-data" as well. "Formdata()" is used to create strings in this style "name=username=16",from javascript code, at the end the data sent to the server will be equal.

  • hmn, weird! I didn’t understand why I didn’t upload the files when I used the tag form with encType ..

  • Ah yes!!! if this is the case,to send files using encType,try to encode the file in Base64,and then decode it from the server side, Node has a great function for this.

Browser other questions tagged

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