Loading an AJAX File Using XMLHttpRequest

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];

+5
source share
3 answers

post_max_size... :

  • PUT POST:

    xhr.open("put", "upload.php", true);

  • FileName FileSize:

    xhr.setRequestHeader("X-File-Name", file.name);
    xhr.setRequestHeader("X-File-Size", file.size);

  • File XHR:

    xhr.send(file);

    , File "files" [type = file] DOM

  • $_SERVER:

    $filename = $_SERVER['HTTP_X_FILE_NAME'];
    $filesize = $_SERVER['HTTP_X_FILE_SIZE'];

  • , php://input:

    $in = fopen('php://input','r');

(1 ) - !!!

FireFox 4+, Chrome 6+, IE10 +

+17

post_max_size ini

+3

Ajax call will not limit the size. This is probably the maximum file size in the php ini file.

+1
source

All Articles