Javascript 使用 XMLHttpRequest 上传 AJAX 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10475313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:31:48  来源:igfitidea点击:

AJAX File Upload with XMLHttpRequest

javascriptajaxfileuploadxmlhttprequest

提问by Danilo Valente

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. Then i decided to use the FormData Object, in the code below

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

And it worked, but only with file sizes low to about 8mb. When I try sending a file that has more than 8mb of size, the var $_FILES['file']becomes empty again

NOTE: the 'file' var corresponds to something like document.getElementsById('fileInput').files[0];

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

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

回答by Opty

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 :

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

  • add custom headers to specify original FileName and 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.send(file);

    Please note that the File object can be obtained directly via the “files” property of your input[type=file] DOM object

  • 使用 PUT 而不是 POST :

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

  • 添加自定义标头以指定原始 FileName 和 FileSize :

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

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

    xhr.send(file);

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

On the server side

在服务器端

  • read the custom headers via $_SERVER :

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

  • read file data using php://input :

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

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

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

  • 使用 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+

回答by user1388342

Change the post_max_sizedirective in the ini file

更改post_max_sizeini 文件中的指令

回答by epascarello

The Ajax call will not limit the size. It is probably the max file size in the php ini file.

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