Upload files with AJAX

Asked

Viewed 4,167 times

4

I am unable to upload some files with AJAX. I need to send 3 files with dynamically generated inputs, so I didn’t use the Multiple attribute.

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

Can 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
}

2 answers

2


If you have every <input type="file" /> that you generate on your own <form> instead of a single <form> with everyone, 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]);
    }
});
  • Got it right, boss. Thanks!

  • @michelmforts :)

1

I had a similar problem with ASP.NET. This is the code I made to solve in my case. Note that I passed the form as 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);

Browser other questions tagged

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