I know that there are many similar questions, but I still have not found a solution to my problem. I am trying to download a file with XMLHttpRequest, so I developed the following code:
var sendFiles = function(url,onload,onerror,file,headers){
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp'),
upload = xhr.upload;
API.addEvent(xhr,'readystatechange',function(){
if(xhr.readyState==4)
if((xhr.status>=200 && xhr.status<300) || xhr.status==304){
this.response = this.response || this.responseText;
onload.call(xhr);
}else onerror.call(xhr);
});
xhr.open('POST',url,true);
for(var n=0;n<headers.length;n++)
xhr.setRequestHeader(headers[n]);
xhr.send(file);
return xhr;
};
And the PHP side of the script:
<?php
header('Content-type: text/html;charset=ISO-8859-1');
$status = 0;
if(@copy($_FILES['file']['tmp_name'],'test\\' . $_FILES['file']['name']))
$status = 1;
else
$err = '0';
echo '{
"status": ' . $status . '
}';
?>;
But var $ _FILES ['file'] seems empty, which means that the file is not sent to the server. Then I decided to use the FormData object in the code below
var sendFiles = function(url,onload,onerror,file,headers){
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp'),
upload = xhr.upload,
formData = new FormData();
formData.append('file',file);
API.addEvent(xhr,'readystatechange',function(){
if(xhr.readyState==4)
if((xhr.status>=200 && xhr.status<300) || xhr.status==304){
this.response = this.response || this.responseText;
onload.call(xhr);
}else onerror.call(xhr);
});
xhr.open('POST',url,true);
for(var n=0;n<headers.length;n++)
xhr.setRequestHeader(headers[n]);
xhr.send(formData);
return xhr;
};
And it worked, but only with file sizes up to 8 MB. When I try to send a file larger than 8 MB, var $_FILES['file']will again become empty
NOTE: the var file corresponds to something like document.getElementsById ('fileInput'). Files [0];