Codeigniter 4:使用move_uploaded_file上传文件

时间:2020-03-09 12:37:34

标签: php codeigniter file-upload codeigniter-4

我刚刚开始将CodeIgniter 3项目移至CodeIgniter4。

一切正常,除了文件上传。

我想将用户上传的文件保留在/ writable / uploads中。下面是我用来将上传的文件移动到所需位置的代码。

            $target_dir = '/writable/uploads/recordings/';
            $target_file = $target_dir . basename($_FILES["gfile"]["name"]);
            $FileType = pathinfo($target_file,PATHINFO_EXTENSION);

            if($FileType != "mp3") {            
             $vmuploadOk = 1;
            }               
            else
             $vmuploadOk = 1;   


            if ($vmuploadOk == 1) {
                $greetfile = $id . "g" . basename($_FILES["gfile"]["name"]);

                $target_filenew = $target_dir . $greetfile;     

                move_uploaded_file($_FILES["gfile"]["tmp_name"], $target_filenew);                 
            }

我认为这是因为CI4将可写文件夹保留在公用文件夹之外。

2 个答案:

答案 0 :(得分:2)

这对我有用,我希望它也对您有用。在codeigniter 4中,请使用它上传文件并将其在控制器中移动。


if($imagefile = $this->request->getFiles())
{
    if($img = $imagefile['gfile'])
    {
        if ($img->isValid() && ! $img->hasMoved())
        {
            $newName = $img->getRandomName(); //This is if you want to change the file name to encrypted name
            $img->move(WRITEPATH.'uploads', $newName);

            // You can continue here to write a code to save the name to database
            // db_connect() or model format

        }
    }
}


        if($img = $this->request->getFile('gfile'))
        {
            if ($img->isValid() && ! $img->hasMoved())
            {
                $newName = $img->getRandomName();
                $img->move('./public/uploads/images/users', $newName);

                // You can continue here to write a code to save the name to database
                // db_connect() or model format

            }
        }

然后在您的html中 使用这个

<input type="file" name="gfile">

我希望这会帮助您引起我的注意。

答案 1 :(得分:1)

您没有使用CodeIgniter的内置函数。代码中显示的所有内容都是PHP函数。如果您想利用内置的CI函数,请浏览@Boominathan Elango链接的文档。

要从请求中获取文件:

sourceString = cfgFile.get('source') sourceList = list(sourceString[1:-1]) print(sourceList)

根据指定的here

要使用CI功能移动文件,请执行以下操作:

$file = $this->request->getFile('here_goes_input_name');

根据指定的here