How to step enctype="Multipart/form-data" by $.post?

Asked

Viewed 10,470 times

2

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

1 answer

5


Short answer: does not pass!

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

The structure of this method is as follows::

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

Where all parameters except the url are optional. Official documentation.

How then?

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

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

jQuery.ajax( url [, settings ] )

As you can notice the settings parameter (Plainobject) are optional but it is not necessary to explicitly state the first argument url if you set settings and this has (contains) an example "url":

$.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 () {
            // evento de "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:

Browser other questions tagged

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