030.CI4框架CodeIgniter, 文件的上传与移动

01.在View中创建一个upfile.php,作为上传文件的前端,代码如下:

<!doctype html>
<html>
<head>
    <title>10年CI一场梦</title>
</head>
<body>

<form action="<?php echo $POST_URL ?>" method="post" enctype="multipart/form-data">
    <td>
        <input name="upfile" id='upfile' type="file" value="选择文件">
    </td>
    <td style="text-align: center;"><input type="submit" name="submit" value="上传"></td>
</form>

</body>
</html>

 

 

02.我们在控制器中,添加文件上传的后端处理Hello.php,代码如下:

<?php namespace App\Controllers;
// http://127.0.0.1/CI4/public/index.php/hello/
class Hello extends BaseController
{
    public function __construct()
    {
    }

    public function index()
    {
    }

    public function show()
    {
        //判断是否点击了上传按钮
        if (!empty($this->request->getPost("submit"))) {
            //读取
            $file = $this->request->getFile('upfile');
            //查看文件类的各种属性
            ShowMessage($file);
            //如果上传没问题,切没有被移动过
            if ($file->isValid() && !$file->hasMoved()) {
                $file->move(WRITEPATH . 'myfiles');
            }
            //    "path"             => "C:\Users\Super\AppData\Local\Temp\php3568.tmp",
            //    "originalName"     => "Welcome to CodeIgniter.html",
            //    "name"             => "Welcome to CodeIgniter.html",
            //    "originalMimeType" => "text/html",
            //    "error"            => 0,
            //    "hasMoved"         => false,
            //    "size"             => 5593,
            //    "pathName"         => "C:\Users\Super\AppData\Local\Temp\php3568.tmp",
            //    "fileName"         => "php3568.tmp";
        }
        //显示View页面
        $data = array('POST_URL' => base_url('public/index.php/hello/show'),);
        echo view('upfile', $data);
    }


}

 

 

03.我们打开浏览器,访问一下http://localhost/CI4/public/index.php/hello/show,并上传一个文件,效果如下:

 

 

04.我们发现,我们上传的文件,已经被传到了我们定义的myfiles文件夹中了

 

 

原创不易,如果您认为这篇文章有价值,认同作者的付出,可以微信二维码打赏任意金额给作者(微信号:382477247)哦,谢谢。

 

posted @ 2020-03-01 23:57  像一棵海草海草海草  阅读(832)  评论(0编辑  收藏  举报