简体   繁体   English

使用XMLHttpRequest上传AJAX文件

[英]AJAX File Upload with XMLHttpRequest

I know there are a lot of similar questions, but I still haven't found a solution for my problem. 我知道有很多类似的问题,但我仍然没有找到解决问题的方法。 I'm trying to upload a file with XMLHttpRequest, so I developed the code below: 我正在尝试使用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;
};

And the PHP-side script is: 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 . '
}';
?>;

But the var $_FILES['file'] seems to be empty, which means that the file isn't being sent to the server. 但是var $ _FILES ['file']似乎是空的,这意味着文件没有被发送到服务器。 Then i decided to use the FormData Object, in the code below 然后我决定在下面的代码中使用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;
};

And it worked, but only with file sizes low to about 8mb. 它有效,但只有文件大小低至约8mb。 When I try sending a file that has more than 8mb of size, the var $_FILES['file'] becomes empty again 当我尝试发送大小超过8mb的文件时,var $_FILES['file']再次变空

NOTE: the 'file' var corresponds to something like document.getElementsById('fileInput').files[0]; 注意:'file'var对应于document.getElementsById('fileInput')。files [0];

To avoid the post_max_size limitation problem... but also out of memory problems on both sides : 为了避免post_max_size限制问题...而且双方都存在内存不足的问题:

On the client side 在客户端

  • use PUT instead of POST : 使用PUT而不是POST:

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

  • add custom headers to specify original FileName and FileSize : 添加自定义标头以指定原始FileName和FileSize:

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

  • use the File object directly in your XHR send method : 直接在XHR发送方法中使用File对象:

    xhr.send(file);

    Please note that the File object can be obtained directly via the “files” property of your input[type=file] DOM object 请注意,可以通过输入[type = file] DOM对象的“files”属性直接获取File对象

On the server side 在服务器端

  • read the custom headers via $_SERVER : 通过$ _SERVER读取自定义标头:

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

  • read file data using php://input : 使用php:// input读取文件数据:

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

You'll then be able to send very big files (1GB or more) without any limitation!!! 然后你就可以发送非常大的文件(1GB或更多),没有任何限制!

This code works for FireFox 4+, Chrome 6+, IE10+ 此代码适用于FireFox 4 +,Chrome 6 +,IE10 +

更改ini文件中的post_max_size指令

The Ajax call will not limit the size. Ajax调用不会限制大小。 It is probably the max file size in the php ini file. 它可能是php ini文件中的最大文件大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM