【问题标题】:Multiple file upload php for loop多个文件上传php for循环
【发布时间】:2018-06-10 08:33:18
【问题描述】:

我正在编写一个应该上传多个文件的脚本。 我有这个html结构

HTML

<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="test[]" multiple="multiple">
<button type="submit">Test upload</button>
</form>

这是我写的php上传类脚本。

PHP

<?php 

class Uploader{

public function upload($files){ 

        $this->files = count($files['name']);

        try{

                for($i = 0; $i < $this->files; $i++){

                    $this->error = $files['error'][$i];
                    $this->tmp_name = $files['tmp_name'][$i];
                    $this->name = basename($files['name'][$i]);
                    $this->size = $files['size'][$i];

                    if($this->error == UPLOAD_ERR_OK){

                        if(is_uploaded_file($this->tmp_name)){

                            move_uploaded_file($this->tmp_name, "$this->path/$this->name");

                        return 'ok';

                    } else {

                        throw new Exception('Error tmp file');

                    } 

                } else {

                throw new Exception('Error');

                }
            }

    }
    catch(Exception $e){

            return $e->getMessage();

    }
}

}
?>

我过去使用for() 循环执行多个上传任务没有问题,但现在它只会上传一个文件。我也在 stackoverflow 上搜索过,有些人不鼓励使用 foreach() 循环来上传多个文件。谁能建议我解决这个问题?

【问题讨论】:

    标签: php file-upload upload


    【解决方案1】:

    您在move_uploaded_file 之后调用return 'ok';,这会在第一个文件上传后中断 for 循环.. 只需删除该行就可以了..

    【讨论】:

    • 感谢您的澄清。我已经把return移到了上传操作完成后,现在可以正常运行了。
    【解决方案2】:

    如果从函数内部调用,return 语句会立即结束当前函数的执行,并将其参数作为函数调用的值返回。

    Here's 一个很棒的脚本,我发现它可以通过 PHP 上传多个文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多