5

After a whole-day's study && trying, i finally give up upload files by pure AJAX (ps: this post How can I upload files asynchronously with JQuery? buried my last hope)

My question may be a little meaningless, but i still wanna know why ajax(or XMLHttpRequest) can't handle this? why can't the files transfered like the real httprequest?

3
  • 2
    Because JavaScript can't read local files - at least not without the help of some HTML 5 API magic.
    – Pekka
    Commented Sep 29, 2011 at 9:16
  • @PeKKa That means AJAX request(with js) and Form request(with html) are totally different things? Even to the browsers?
    – rhapsodyn
    Commented Sep 29, 2011 at 10:02
  • 2
    not really - you can build any kind of request using Ajax. It's just accessing the local file that isn't possible in JavaScript for security reasons.
    – Pekka
    Commented Sep 29, 2011 at 10:04

2 Answers 2

8

Javascript cannot read local files for security reasons, so we can't send the data using AJAX.

However you can POST a standard HTML form, and set the form target to be an invisible iframe on the page. This iframe can then use server side code to handle the upload.

If your reason to use AJAX is because you'd like a progress bar as the file is uploading, using this method you can use a server-side static variable to store the progress of the file upload, then use AJAX to make a simple, timed request to another HTTP page which just returns the upload progress.

2

Just as an updated answer in case someone Googles this, XMLHttpRequest level 2 does support AJAX submittal of file inputs.

Browser support:

http://caniuse.com/xhr2

It uses the FormData Javascript object.

How to send FormData objects with Ajax-requests in jQuery?

Don't forget to turn off processData and contentType if you're doing this.

var fd = new FormData();    
fd.append( 'file', input.files[0] );

$.ajax({
  url: 'http://example.com/script.php',
  data: fd,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){
    alert(data);
  }
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.