1

在我的表单提交中,我有:

var formData = new FormData();

        for (var i = 0; i < ctx.files.length; i++) {
            formData.append('file[]', ctx.files[i]);

        }

在我的服务器端,我只是转储 $_POST。

我得到:

array(1) {
 ["file"]=>
  array(1) {
    [0]=>
   string(17) "[object FileList]"
 }
}

它以字符串的形式出现,我怎样才能将它作为文件数组获取?

这是整个请求:

var formData = new FormData();

        for (var i = 0; i < ctx.files.length; i++) {
            formData.append('file[]', ctx.files[i]);
            //formData.push(ctx.files[i]);
        }

        // now post a new XHR request
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/site-manager-gateway/add-content');
        xhr.onload = function () {
            if (xhr.status === 200) {
                console.log('all done: ' + xhr.status);
            } else {
                console.log('Something went terribly wrong...');
            }
        };

        xhr.send(formData);
4

1 回答 1

0

丢失的东西

在发送前添加:
xhr.setRequestHeader("Content-Type","multipart/form-data");

访问文件

之后,可以像这样访问文件:

$count = count($_FILES['file']['name']);
for($i=0; $i<$count; $i++)
{
   echo 'Uploaded File With FileName: '.$_FILES['file']['name'][$i].'<br/>';

}

更多信息:$_FILES 变量

http://www.php.net/manual/en/reserved.variables.files.php

如果您转到此链接,您将看到该$_FILES变量将如下所示:

array(1) {
    ["upload"]=>array(5) {
        ["name"]=>array(3) {
            [0]=>string(9)"file0.txt"
            [1]=>string(9)"file1.txt"
            [2]=>string(9)"file2.txt"
        }
        ["type"]=>array(3) {
            [0]=>string(10)"text/plain"
            [1]=>string(10)"text/plain"
            [2]=>string(10)"text/plain"
        }
        ["tmp_name"]=>array(3) {
            [0]=>string(14)"/tmp/blablabla"
            [1]=>string(14)"/tmp/phpyzZxta"
            [2]=>string(14)"/tmp/phpn3nopO"
        }
        ["error"]=>array(3) {
            [0]=>int(0)
            [1]=>int(0)
            [2]=>int(0)
        }
        ["size"]=>array(3) {
            [0]=>int(0)
            [1]=>int(0)
            [2]=>int(0)
        }
    }
}

“可是……我的文件呢??”

您的文件位于临时文件夹中(在 linux 中,默认为 /tmp)。
从此临时文件夹中恢复文件的唯一方法是在每个文件上使用 php 函数:

move_uploaded_file

根据php文档

"此函数检查文件名指定的文件是否为有效的上传文件(即通过 PHP 的 HTTP POST 上传机制上传)。如果文件有效,则将其移动到目标指定的文件名。

如果对上传文件进行的任何操作都可能向用户甚至同一系统上的其他用户泄露其内容,则这种检查尤其重要。”

move_uploaded_file 用法

这就是你应该这样做的方式。如果您上传的目录称为“上传”,则:

<?php
$uploads_dir = '/uploads';
foreach ($_FILES["file"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["file"]["tmp_name"][$key];
        $name = $_FILES["file"]["name"][$key];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}
?>

这会将所有文件保存在“/uploads”目录中。

于 2013-09-18T13:24:28.707 回答