Upload upload files with AJAX

4

I am not able to send some upload files with AJAX. I need to send 3 files with dynamically generated inputs, so I did not use the multiple attribute.

By firing the event, I get to the xhr.send (files), which does not "play" the PHP file.

Can you help me?

function UploadFile(file){
    var files = file[0];
    var xhr = new XMLHttpRequest();
    var fd = new FormData();

    fd.append( "arquivo", files, files.name );
    xhr.open("POST", "Produtos/upload", true);

    console.log(files.name); //imprime o nome certinho da imagem

    xhr.setRequestHeader("X_FILENAME", files.name);
    xhr.send(fb);
}


$(".btn-comprar").click(function (e) {

    e.preventDefault();
    var form = $("#upload");
    var arquivos = $(".arquivos");

    for (var i = 0; i < arquivos.length; i++) {
        UploadFile(arquivos[i].files);
    }
});

In PHP:

public function upload(){
    $this->autoRender = false;
    debug($_FILES); // nao imprime
    echo "ok"; //nao imprime
}
    
asked by anonymous 14.10.2016 / 23:54

2 answers

2

If you have every <input type="file" /> you generate on your own <form> instead of a single <form> with all, then:

function UploadFile(form) {
    var formData = new FormData(form); 

    $.ajax({
         url: 'Produtos/upload',
         type: 'POST',
         data: formData,
         async: false,
         cache: false,
         contentType: false,
         enctype: 'multipart/form-data',
         processData: false,
         success: function (response) {
             alert(response);
         }
         fail: function() {
             alert("Servidor em baixo ou falha de rede");
         }
    });
}

$(".btn-comprar").click(function (e) {

    e.preventDefault();
    var forms = $("form");

    for (var i = 0; i < forms.length; i++) {
        UploadFile(forms[i]);
    }
});
    
15.10.2016 / 01:07
1

I had a problem similar to ASP.NET. This is the code I have made to resolve in my case. Note that I passed the form as a parameter in the FormData constructor.

window.addEventListener("submit", function (e) {
    var form = e.target;
    if (form.getAttribute("enctype") === "multipart/form-data") {
        if (form.dataset.ajax) {
            e.preventDefault();
            e.stopImmediatePropagation();
            var loadingSelector = $(form).data("ajax-loading");
            var xhr = new XMLHttpRequest();
            xhr.open(form.method, form.action);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    $(form.dataset.ajaxUpdate).html(xhr.responseText);
                    $('a[IsAjax="True"]').click(function (e) {
                        e.preventDefault();
                        redirecionar($(this).attr("href"));
                    });
                    $.validator.unobtrusive.parse($(form.dataset.ajaxUpdate));
                    $('form').validateBootstrap();
                    $(loadingSelector).hide();
                }
            };
            var formData = new FormData(form);
            formData.append('X-Requested-With', 'XMLHttpRequest');
            xhr.send(formData);
            if (loadingSelector) {
                $(loadingSelector).show();
            }
        }
    }
}, true);
    
15.10.2016 / 01:18