0

i've been stuck with this problem for a while.

I need to realize a simple ajax file upload to server, without showing the user a file form and immediate presentation of the uploaded picture I've been trying to use this plugin: http://valums.com/ajax-upload/, but it doesn't work. The request succesfully reaches the server (and then returns to client), but when I'm trying to access $_FILES array (yes, it's PHP), it is empty!

The code that manages sending is this:

    xhr.open("POST", queryString, true);
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
    xhr.setRequestHeader("Content-Type", "application/octet-stream");
    xhr.send(file);

I've been trying to google this problem, but all links in unison say, that you can't upload files with XHR. But this plugin seems to be pretty popular and legit - so, what am I doing wrong? Thanks!

kubetz
  • 8,485
  • 1
  • 22
  • 27
opportunato
  • 621
  • 1
  • 6
  • 10
  • 1
    I'm guessing it uses the new html5 apis for file upload on browsers that support it and fallsback to iframes on older browsers.. You can't upload files with regular XHR. Are you getting any sort of error on the page? And have you added the multipart attribute to your form? – JohnP Dec 07 '11 at 06:41
  • At what point are you trying to access the $_FILES array? Can you post your file processing PHP code? – Brian Driscoll Dec 07 '11 at 06:41
  • But in fact it doesn't fallback - it thinks that my version is super cool and uses it instead of iframes. The code for checking is: return ('multiple' in input && typeof File != "undefined" && typeof (new XMLHttpRequest()).upload != "undefined" ); – opportunato Dec 07 '11 at 06:45
  • No there aren't any errors. The PHP script is simply print_r($_FILES) - printing an empty array as a result – opportunato Dec 07 '11 at 06:47

1 Answers1

1

Reading file with the new HTML5 filereader API and sending it with XHR, I don't think it is the same as HTTP file upload in which case $_FILES is used. The data is base64encoded and sent with POST method.

zuo
  • 1,061
  • 1
  • 12
  • 27
  • Yes, I've thought of that, but the $_POST is empty too. The Firebug console is definitely full with data though. – opportunato Dec 07 '11 at 07:02
  • Actually there is a piece of sample code on github repo:[here](https://github.com/valums/file-uploader/blob/master/server/php.php) – zuo Dec 07 '11 at 11:30