1

I know this has been asked a lot....but none of the answers I am coming across are helping. This is something ive done many times before...but on this occasion, im hitting a problem.

Im am trying to upload a zip file, via ajax, without submitting the form, just the field. I append the file to the formdata object...but the formdata is always empty (checking it before i send via ajax). $_FILES array server side is also always empty.

Can anyone see whats wrong, ive tried many variations... If i console.log(jQuery("#file_import")[0].files[0]); I see the file data.

                var fileInput = jQuery("#file_import")[0];
                var formData = new FormData();
                formData.append("zipfile",fileInput.files[0]);

                jQuery.ajax("/whatever/url", {
                    method: "POST",
                    data: formData,
                    dataType: "json",
                    cache: false,
                    contentType: false,
                    processData: false,
                    onSuccess: function(response){
                        alert("whatever...");
                    }
                });

Thanks in advance. Shaun

1 Answer 1

1

When you say "the formdata is always empty," are you trying to check it using formdata.entries(), or are you using formData.get('zipfile')? I think only the second of these will work.

EDIT: here is my exact code, client and server side.

$(document).ready(function() {

    $('#start').click(function() {
        var fileInput = $("#file_import")[0];
        var formData = new FormData();
        formData.append("zipfile",fileInput.files[0]);

        $.ajax("test.php",{
            method: "POST",
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function(response){
                $('#output').html(response);
            }
        });
    });


});

HTML:

<input type="file" id="file_import"/>
<button id="start">Start</button>
<div id="output">
</div>

PHP:

<?php

print_r($_FILES);
$t = $_FILES['zipfile'];

$date = new DateTime();
$d = $date->format('Y-m-d_H-i-s');

move_uploaded_file($t['tmp_name'], "asdf_$d.zip");

?>
Sign up to request clarification or add additional context in comments.

3 Comments

Are you sure? I removed that line, tested in firefox, my usual browser...and $_FILES was still empty server side. Switched to chrome...and get the same :(
I can confirm that formData.get('zipfile') gives me the filename...but serverside $_FILES is still empty.
Just posted all my code...works on firefox/chrome, with apache/php web server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.