没有收到来自$ _FILES的数据

时间:2013-08-29 19:48:45

标签: php javascript jquery

我正在使用html5 dropzone上传图片,带有javascript

var dropZone = $('#dropZone'),
    maxFileSize = 1000000,
    img_id = 0;

// 
if (typeof (window.FileReader) == 'undefined') {
    dropZone.text('NO BROWSER SUPPORT!');
    dropZone.addClass('error');
}

// 
dropZone[0].ondragover = function () {
    dropZone.addClass('hover');
    return false;
};

// 
dropZone[0].ondragleave = function () {
    dropZone.removeClass('hover');
    return false;
};

// 
dropZone[0].ondrop = function (event) {
    event.preventDefault();
    dropZone.removeClass('hover');
    dropZone.addClass('drop');

    var file = event.dataTransfer.files[0];

    // 
    if (file.size > maxFileSize) {
        dropZone.text('SO BIG FILE!');
        dropZone.addClass('error');
        return false;
    }

    // 
    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener('progress', uploadProgress, false);
    xhr.onreadystatechange = stateChange;
    xhr.open('POST', '/admin/admin.api.php');
    xhr.setRequestHeader('X-FILE-NAME', file.name);
    xhr.send(file);
};

// 
function uploadProgress(event) {
    var percent = parseInt(event.loaded / event.total * 100);
    dropZone.text('Загрузка: ' + percent + '%');
}

// 
function stateChange(event) {
    if (event.target.readyState == 4) {
        if (event.target.status == 200) {
            dropZone.text('SUCCESS!');
        } else {
            dropZone.text('FAIL!');
            dropZone.addClass('error');
        }
    }

}

标题和数据:

Request URL:http://***.com/admin/admin.api.php
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:uk-UA,uk;q=0.8,ru;q=0.6,en-US;q=0.4,en;q=0.2
Connection:keep-alive
Content-Length:86016
Content-Type:image/jpeg
Host:***.com
Origin:http://***.com
Referer:http://***.com/admin/
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.62 Safari/537.36
X-FILE-NAME:image.jpeg
Response Headersview source
Connection:Keep-Alive
Content-Encoding:gzip
Content-Length:132
Content-Type:text/html
Date:Thu, 29 Aug 2013 19:29:00 GMT
Keep-Alive:timeout=15, max=100
Server:Apache/2.2.16 (Debian)
Vary:Accept-Encoding
X-Powered-By:PHP/5.3.3-7+squeeze16

php脚本

    <?
    print_r($_POST);
print_r($_GET);
print_r($_FILES);
    ?>

返回

Array()Array()Array()

1 个答案:

答案 0 :(得分:2)

只有在您将文件作为多部分表单数据发送时才会填充$_FILES数组,请尝试使用FormData

var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', uploadProgress, false);
xhr.onreadystatechange = stateChange;
xhr.open('POST', '/admin/admin.api.php');
var formData = new FormData();
formData.append('file', file);
xhr.send(formData);