Pass files by ajax

Asked

Viewed 110 times

1

I am creating the product registration form of a website, and in it, all forms are submitted by ajax to an api. The problem is that in this particular form I need to send images to the server. I am trying to use the Formdata object to send, but without success. Follow the javascript code I am using:

$("#formProduto").submit((e) => {
    var formProduto = document.getElementById('formProduto');
    var formData = new FormData(formProduto);
    $.ajax("/admin/produto/api", {
        type: "POST",
        data: formData,
        success: (data) => {
            //Sucesso
        }
    }
    return e.preventDefault();
});

Using data: $("#formProduto").serialize() (without the file, of course) ajax works normally, when I change the above code it just ignores the e.preventDefault(); and submit the form to the page itself.

1 answer

3


First check if your form has the attribute enctype="multipart/form-data" which allows you to upload files, then change your code to something like:

var fData = new FormData($('#formProduto')[0]);
$.ajax({
  url : "/admin/produto/api",
  dataType: 'json',
  processData: false,
  data: fData,
  type: 'POST',
  contentType: false,
  success : function() {
    console.log("success", success);        
  },
  complete: function() {
    console.log("complete", complete);
  },
  error: function() {
    console.log("error", error);        
  }
});

Adding the options processData: false and contentType: false

  • Even using ajax to submit the form I need to set the enctype?

  • Form information is not coming to the server-side (Nodejs/Express).

  • Had done with PHP, with Node may be a different way. Without the enctype the file fields are not sent together with the other fields. Submit the form is see the fields being passed in the request, if using Chrome see in the Network tab.

  • The module I am using does not support sending files, I will have to use another to get the information, change my entire backend Ahhhhh, mas vlw ai cara

  • Blz, good luck with the refactoring.

Browser other questions tagged

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