llagerlof
4/25/2018 - 7:09 PM

How to POST form data with multiple files upload using jQuery

How to POST form data with multiple files upload using jQuery

<script type="text/javascript">

// This example expect a json return from receiver_script.php
// Remove unnecessary logs and alerts as needed.

var form_data = new FormData();
form_data.append("first_name", $("#first_name").val());
form_data.append("age", $("#age").val());
var file_data = $("#attachment").prop("files");
$.each(file_data, function (i, file) {
    form_data.append("anexo["+i+"]", file);
});

$.ajax({
    type: "POST",
    contentType: false,
    processData: false,
    url: "receiver_script.php",
    data: form_data,
    dataType: "json",
    cache: false,
    success: function(result) {
        console.log("result:", result);
        $.each(result, function(key, value) {
            console.log(key);
            console.log(value);
        });
    },
    error: function(error) {
        alert("error: " + error.responseText);
        console.log("error: " + error.responseText);
    }
});

</script>