使用 XMLHttpRequest 上传 AJAX 文件 [英] AJAX File Upload with XMLHttpRequest

查看:20
本文介绍了使用 XMLHttpRequest 上传 AJAX 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多类似的问题,但我仍然没有找到解决我问题的方法.我正在尝试使用 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:

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 对象

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

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

推荐答案

为了避免 post_max_size 限制问题...而且两边内存不足的问题 :

To avoid the post_max_size limitation problem... but also out of memory problems on both sides :

  • 使用 PUT 而不是 POST :

  • 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);

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

use the File object directly in your XHR send method :

xhr.send(file);

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

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

  • read the custom headers via $_SERVER :

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

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

read file data using php://input :

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

然后您就可以无限制地发送非常大的文件(1GB 或更多)!!!

You'll then be able to send very big files (1GB or more) without any limitation!!!

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

这篇关于使用 XMLHttpRequest 上传 AJAX 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆