Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload file with Ajax XMLHttpRequest

I am trying to send file with XMLHttpRequest with this code.

var url= "http://localhost:80/...."; $(document).ready(function(){     document.getElementById('upload').addEventListener('change', function(e) {         var file = this.files[0];         var xhr = new XMLHttpRequest();         xhr.file = file; // not necessary if you create scopes like this         xhr.addEventListener('progress', function(e) {             var done = e.position || e.loaded, total = e.totalSize || e.total;             console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');         }, false);         if ( xhr.upload ) {             xhr.upload.onprogress = function(e) {                 var done = e.position || e.loaded, total = e.totalSize || e.total;                 console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');             };         }         xhr.onreadystatechange = function(e) {             if ( 4 == this.readyState ) {                 console.log(['xhr upload complete', e]);             }         };         xhr.open('post', url, true);         xhr.setRequestHeader("Content-Type","multipart/form-data");         xhr.send(file);     }, false); }); 

I get this error: T

The request was rejected because no multipart boundary was found.

What am I doing wrong?

like image 860
Sedat Başar Avatar asked Jun 02 '11 06:06

Sedat Başar


People also ask

How do I upload a file using XMLHttpRequest?

You have to use the FormData object to wrap the file into a multipart/form-data post data object: var formData = new FormData(); formData. append("thefile", file); xhr. send(formData);

Can we upload file using AJAX?

File upload is not possible through AJAX. You can upload file, without refreshing page by using IFrame .


1 Answers

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData(); formData.append("thefile", file); xhr.send(formData); 

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

like image 172
timdream Avatar answered Sep 25 '22 03:09

timdream