简体   繁体   中英

Ajax File Upload upload.php not Getting Called

I'm new to jQuery/Ajax and I am trying to upload a file like so:

var fd = new FormData();
fd.append('file', file);

$.ajax({
  xhr: function() {
    var xhrobj = $.ajaxSettings.xhr();
    if (xhrobj.upload) {
      xhrobj.upload.addEventListener('progress', function(e) {
        var percent = 0;

        if (e.lengthComputable) {
          percent = Math.floor(e.loaded / e.total * 100);
        }

        progressDiv.find('progress').val(percent);
        progressDiv.find('b').html(percent + '%');
      });
    }
  },
  type: 'POST',
  url: 'upload.php',
  data: fd,
  success: function(data) {
    progressDiv.find('progress').val(100);
    progressDiv.find('b').html('100%');

    alert(data);
  },
  error: function() {
    alert('Error uploading!');
  }
});

My upload.php file looks like this:

<?php
file_put_contents('log.txt', "LOG\n");
file_put_contents('log.txt', implode(', ', $_FILES) . "\n", FILE_APPEND);
$target = 'upload/' . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
  file_put_contents('log.txt', "SUCCESS\n", FILE_APPEND);
} else {
  file_put_contents('log.txt', "FAILURE\n", FILE_APPEND);
}
?>

The problem is that the progress bars are remaining at 0 and the no alert ever appears. Also nothing is being written to the log file, meaning that upload.php is not even being called.

What am I doing wrong?

EDIT:

After searching for a while I stumbled across this nifty little question: Submitting a file with jQuery.ajax gives TypeError

So adding contentType: false and processData: false seems to have done something. Now I get the alert "Error uploading", but I still don't think upload.php is being called as nothing is being written to log. Commenting out the xhr stuff after making those changes allows the upload to complete. Now the question becomes what is wrong with the xhr stuff?

What is 'log'?

file_put_contents('log', "LOG\n");

I bet if you looked at your webserver error log the PHP script would be found to be choking on trying to write to 'log'.

EDIT

Here's an existing question that appears to show correctly how to do what you're trying to do. If you're still not getting the result you expect, I would still suspect there's something wrong with your file paths. Full error reporting should clarify the issue

update progress bar using ajax request seconds

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM