AJAX File Upload with XMLHttpRequest

AJAX File Upload with XMLHttpRequest

本文关键字:XMLHttpRequest with Upload File AJAX      更新时间:2023-09-26

我知道有很多类似的问题,但我仍然没有找到解决问题的方法。我正在尝试使用 XMLHttpRequest 上传文件,所以我开发了下面的代码:

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

PHP 端脚本是:

<?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 . '
}';
?>;

但是 var $_FILES['file'] 似乎是空的,这意味着该文件没有发送到服务器。然后我决定在下面的代码中使用 FormData 对象

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

它有效,但仅限于文件大小低至约8mb的情况。当我尝试发送大小超过 8mb 的文件时,var $_FILES['file']再次变为空

注意:"file"var对应于类似document.getElementsById('fileInput').files[0];

为了避免post_max_size限制问题...而且双方都有内存不足的问题:

在客户端

  • 使用 PUT 而不是 POST :

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

  • 添加自定义标头以指定原始文件名和文件大小:


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

  • 直接在 XHR 发送方法中使用 File 对象:

    xhr.send(file);

    请注意,File 对象可以直接通过 input[type=file] DOM 对象的 "files" 属性获取

在服务器端

  • 通过 $_SERVER 读取自定义标头:


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

  • 使用 php://input 读取文件数据:

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

然后,您将能够不受任何限制地发送非常大的文件(1GB 或更多!!

此代码适用于FireFox 4+,Chrome 6 +,IE10+

更改 ini 文件中的 post_max_size 指令

Ajax 调用不会限制大小。这可能是 php ini 文件中的最大文件大小。