skip to Main Content

Im trying to send file to api using ajax , but form-data always null in both cases mentioned below

<form id="myformdoc">
    <input type="file" size="45" name="file" id="file">
</form>

           <script>
          $('#file').on("change", function () {
        
          // var formdata = new FormData($('form').get(0));
          
          let myForm = document.getElementById('myformdoc');
          let formData = new FormData(myForm);

    
        $.ajax({
            url: url,
            type: 'POST',
            data: formdata ,
            cache: false,
            processData: false,
            contentType: false,
            success: function (color) {
                ;
            },
            error: function () {
                alert('Error occured');
            }
        });
    
});
</script>

Any idea why form-data always null ?

2

Answers


  1. Try adding multipart/form-data in contentType parameter.

    Login or Signup to reply.
  2. You need to use
    formData append to add files to your formData function.

    Change your jQuery code to this below and it will work fine and you can get the files on your backend to save them.

    If you have other inputs in your form you can append them as well if you like to.

    formData.append('file', $(this)[0].files[0])
    

    Demo:

    $('#file').on("change", function() {
      //Initialize formData
      let formData = new FormData();
      console.log($(this)[0].files)
      formData.append('file', $(this)[0].files[0]) //append files to file formData
    
      $.ajax({
        url: 'url',
        type: 'POST',
        data: formData,
        cache: false,
        processData: false,
        contentType: false,
        success: function(color) {
          console.log(color);
        },
        error: function() {
          alert('Error occured');
        }
      });
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form enctype="multipart/form-data">
        <input type="file" size="45" name="file" id="file">
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search