How do I pass enctype="multipart / form-data" to $ .post?

2

How do I send a form via $ .post with a file type input where the form has enctype="multipart / form-data"? All other fields make insertion the problem that the file does not pass because it does not read as enctype="multipart / form-data".

    
asked by anonymous 23.12.2017 / 20:25

1 answer

2
  

Short answer: does not pass!

The jQuery.post() "aka" $.post() method was designed to "load server data using a HTTP POST request" parameters of type String or PlainObject are optional, although these parameters serve only to meet the requirements of the request very common to use them to send data to the bad server, multiparty/form-data is not supported in this method.

The structure of this method is as follows:

jQuery.post( url [, data ] [, success ] [, dataType ] )

Where all parameters with the exception of url are optional. Official Documentation .

  

How to do it then?

Simple, use the method jQuery.ajax() "aka" $.ajax() which accepts numerous configuration options. Official Documentation .

The structure of the $.ajax() method follows the following basis:

jQuery.ajax( url [, settings ] )

As you can see the settings parameter ( PlainObject ) are bad options, it is not necessary to explicitly declare the first argument url if you set configurations and it has (contain) an "url" example:

$.ajax({
    url: 'https://awesomedomain.com'
})
  

A complete example:

<!DOCTYPE html>
<html>
<head>
    <title>Titulo</title>
</head>
<body>
    <form method="POST" enctype="multipart/form-data" id="fileUploadForm">
        <input type="text" name="extraField"><br><br>
        <input type="file" name="files"><br><br>
        <input type="file" name="files"><br><br>
        <input type="submit" value="Submit" id="btnSubmit">
    </form>

    <!-- load jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script><script>$(document).ready(function(){//eventode"submit"
            $("#btnSubmit").click(function (event) {
                // parar o envio para que possamos faze-lo manualmente.
                event.preventDefault();
                // capture o formulário
                var form = $('#fileUploadForm')[0];
                // crie um FormData {Object}
                var data = new FormData(form);
                // caso queira adicionar um campo extra ao FormData
                // data.append("customfield", "Este é um campo extra para teste");
                // desabilitar o botão de "submit" para evitar multiplos envios até receber uma resposta
                $("#btnSubmit").prop("disabled", true);
                // processar
                $.ajax({
                    type: "POST",
                    enctype: 'multipart/form-data',
                    url: "/coolurl/upload",
                    data: data,
                    processData: false, // impedir que o jQuery tranforma a "data" em querystring
                    contentType: false, // desabilitar o cabeçalho "Content-Type"
                    cache: false, // desabilitar o "cache"
                    timeout: 600000, // definir um tempo limite (opcional)
                    // manipular o sucesso da requisição
                    success: function (data) {
                        console.log(data);
                        // reativar o botão de "submit"
                        $("#btnSubmit").prop("disabled", false);
                    },
                    // manipular erros da requisição
                    error: function (e) {
                        console.log(e);
                        // reativar o botão de "submit"
                        $("#btnSubmit").prop("disabled", false);
                    }
                });
            });
        });
    </script>
</body>
</html>

Other similar topics here in the community:

23.12.2017 / 21:49