繁体   English   中英

Codeigniter 4:使用 move_uploaded_file 上传文件

[英]Codeigniter 4: Uploading files with move_uploaded_file

我刚刚开始将 CodeIgniter 3 项目迁移到 CodeIgniter 4。

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

我想将用户上传的文件保存在 /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 将可写文件夹保留在公用文件夹之外。

这对我有用,我希望它也对你有用。 在 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">

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

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

从请求中获取文件:

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

作为指定在这里

使用 CI 功能移动文件:

$file->move(WRITEPATH.'uploads', $newName);

作为指定在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM