文件上传与数组无法正常工作

时间:2015-08-02 21:43:42

标签: php

您好我正在尝试将多个文件作为数组上传但收到错误:

Warning: move_uploaded_file() expects parameter 1 to be string, array given in

我的代码如下:

PHP

  foreach ($_FILES as $file) {  
     $file = rand(1000,100000)."-".$_FILES['file']['name'];
     $file_loc = $_FILES['file']['tmp_name'];
     $file_size = $_FILES['file']['size'];
     $file_type = $_FILES['file']['type'];
     $folder="../../uploads/";
     $moveResult = move_uploaded_file($file_loc,$folder.$final_file); }

HTML:

<div class="field"><label for="file_01">file_01</label><input type="file" name="file[]" multiple></div>
<div class="field"><label for="file_01">file_01</label><input type="file" name="file[]" multiple></div>
<div class="field"><label for="file_01">file_01</label><input type="file" name="file[]" multiple></div>

我如何修复该错误?欢迎任何帮助。

2 个答案:

答案 0 :(得分:4)

您将整个数组加载到$ file_loc(迭代错误):

for($i = 0;$i < count($_FILES['file']['name']);$i++) {
    if($_FILES['error'][$i] === 0) { //checks that a file was uploaded without error on current index
        $file = rand(1000,100000)."-".$_FILES['file']['name'][$i];
        $file_loc = $_FILES['file']['tmp_name'][$i];
        $file_size = $_FILES['file']['size'][$i];
        $file_type = $_FILES['file']['type'][$i];
        $folder="../../uploads/";
        $moveResult = move_uploaded_file($file_loc,$folder.$final_file);
    }
}

如果您将来遇到这样的问题,请记住您可以使用:

print_r($_FILES); //in any case with an array

了解数组的结构。这就是我发现你错误地迭代它的方式。这样的输出如下:

Array
(
    [file] => Array
        (
            [name] => Array
                (
                    [0] => upnp_trace4.log
                    [1] => upnp_trace2.log
                    [2] => upnp_trace1.log
                )
            [type] => Array
                (
                    [0] => text/x-log
                    [1] => text/x-log
                    [2] => text/x-log
                )
            [tmp_name] => Array
                (
                    [0] => /tmp/phps82zof
                    [1] => /tmp/phpcq2oiG
                    [2] => /tmp/phpA2mec7
                )
            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                    [2] => 0
                )
            [size] => Array
                (
                    [0] => 9
                    [1] => 9
                    [2] => 9
                )
        )
)

答案 1 :(得分:1)

这可能是因为您的输入文件具有相同的名称(name =“file []”)。这会创建一个数组。

所以你可能需要这样做:

 //first file
 $moveResult = move_uploaded_file($file_loc[0],$folder.$final_file);
 //second file
 $moveResult = move_uploaded_file($file_loc[1],$folder.$final_file);
 //third file
 $moveResult = move_uploaded_file($file_loc[2],$folder.$final_file);

不要忘记检查是否有三个文件正在上传。