如何读取 php 中的 FormData 文件?

how can I read FormData file in php?

我有一个 ajax 表单数据

<form id="form" action="index.php?id=upload" method="post" enctype="multipart/form-data">

    <input id="files" multiple="true" name="files[]" type="file" />

</form>

我想随后通过数据表单发送此表单。

所以我创建了一个循环 jn jquery 来读取每个文件,所以每个文件我有这个:

var data = new FormData();
        data.append(file.name, file);

        $.ajax({
            url: 'index.php?id=upload',
            type: 'POST',
            contentType: false,
            cache: false,
            processData:false,
            data: data,
            fileName:'files',

在 php 代码中打印 var_dumb($_FILES) 我得到这个结果:

names:"array(1) { ["8_modem_pool_with_small_and_big_jpg"]=> array(5) { ["name"]=> string(35) "8 modem pool with small and big.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(24) "F:\xampp\tmp\php268B.tmp\"
["error"]=> int(0) ["size"]=> int(99790) }}

如何在服务器端获取 $_FILES 值? 我试试

if(isset($_FILES["files"]))
        { 

if(isset($_FILES["file"]))
        {

但其中 none 行不通。

--------编辑------------

感谢您的回答。但他们不是我的答案。

在php时我用

$_FILES["files"]

我收到此错误:

Undefined index

但我可以通过以下代码打印值:

foreach($_FILES as $index => $file) {
 move_uploaded_file($file['tmp_name'],$target.$file['name']); 
}

希望你能理解我....

我想要这样的东西:

if(isset($_FILES["files"]))
{
   //do action for single file
   // do action for array file
}

最新代码适用于普通表单,但不适用于表单数据。

尝试以下操作:

move_uploaded_file( $_FILES['names']['8_modem_pool_with_small_and_big_jpg']['tmp_name'], $target);//target is the new file location and name

对于多个文件使用循环

foreach($_FILES['names'] as $index => $file) {
     $target = '/img/'.$file['name']
     move_uploaded_file( $file['tmp_name'], $target);
}

这取决于你想要什么值。所有这些都在数组中可见。

如果你想要名字,你可以使用

$_FILES['names']['8_modem_pool_with_small_and_big_jpg']['tmp_name']

要将文件存储到特定位置,您可以使用

move_uploaded_file( $_FILES['names']['8_modem_pool_with_small_and_big_jpg']['tmp_name'], $myFile);

您可以尝试使用 for 循环遍历这个 3 级关联数组:

if(isset($_FILES['8_modem_pool_with_small_and_big_jpg'])){
    for($i=0;$i < count($_FILES['8_modem_pool_with_small_and_big_jpg']['name']);$i++){
        //Do whatever with the file:
        echo $_FILES['8_modem_pool_with_small_and_big_jpg']['name'][$i];
        echo $_FILES['8_modem_pool_with_small_and_big_jpg']['type'][$i];
        echo $_FILES['8_modem_pool_with_small_and_big_jpg']['tmp_name'][$i];
    }
}