0

I wish to upload img via ajax and my ajax post can't be received by my php.

function handleFileSelect(evt) {
    files = evt.target.files; // FileList object

    $('.thumb-canvas' + filesId).css('display','block');

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
          document.getElementById('list' + filesId).insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);

      //upload ajax

  var xhr = new XMLHttpRequest();

  var formData = new FormData();

  formData.append('file',files);

  xhr.upload.addEventListener("loadstart", function(e){

    $("#progressbar").show();

    $("#percentage").show();

  }, false);


  xhr.open("POST", "upload.php");

  xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');

  xhr.send(formData);



    }
  }

my php

echo var_dump($_FILES['file']);

I get NULL. I also tried echo var_dump($_FILES['files']);

I try use $_POST to check if something witin, yes it's not empty, but I wonder why I can't use the $_FILES

user3346088
  • 109
  • 1
  • 7
  • There is no element `file` inside $_FILES. Try dumping the whole superglobal instead: `var_dump($_FILES);` – arkascha Mar 03 '14 at 09:53
  • 1
    xhr.overrideMimeType('text/plain; charset=x-user-defined-binary'); Ive never used AJAX for uploads, but isnt this the wrong mimetype? I think you need something like in usual HTML, `multipart/form-data`? Im unsure, could be another mistake, but a file is not `text/plain`. – Realitätsverlust Mar 03 '14 at 09:52

1 Answers1

-1
'text/plain; charset=x-user-defined-binary'

This is not data encoding for POST file transfer, so PHP cannot find files as data must be multipart form data.

You can make your script to send it correctly, then PHP will find files into $_FILES. Or you can make custom data transfer (Something like here Using HTML5 file uploads with AJAX and jQuery )

Community
  • 1
  • 1
SergeS
  • 11,533
  • 3
  • 29
  • 35