javascript - XMLHttpRequest - 发送文件?

标签 javascript php ajax

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

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

最佳答案

缺少东西

发送前添加:
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 documentation :

"This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system."

move_uploaded_file 用法

你应该这样做。如果您的上传目录名为“uploads”,则:

<?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”目录中。

关于javascript - XMLHttpRequest - 发送文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18871106/

相关文章:

javascript - 对 Bootstrap 下拉项选择执行操作

javascript - PHP 循环 Javascript 只显示第一条记录

javascript - 在ie中使用javascript覆盖先前设置的float

php mongodb全文搜索和排序

php - 为 mysql 行使用标识符

javascript - 类型错误 : invalid 'in' operand a from ajax

javascript - 使用 jQuery 伪造加载更多内容(无 AJAX/PHP)

JavaScript 未按顺序运行

jquery - 如何使用 $.ajax(jQuery 或 Zepto)发布对象数组

php - 保存到数据库之前的 Laravel 预览