Codeigniter 4: Uploading files with move_uploaded_file

前端 未结 2 1250
北海茫月
北海茫月 2021-01-23 06:06

I just started moving CodeIgniter 3 project to CodeIgniter 4.

Everything works fine except file upload.

I would like to keep the user uploaded files in /writab

相关标签:
2条回答
  • 2021-01-23 06:19

    You are not using CodeIgniter's built in functions. Everything shown in your code are PHP functions. If you want to leverage built in CI functions, then look through the documentation as linked by @Boominathan Elango.

    To get the file from the request:

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

    As specified here

    To move the file using CI function:

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

    As specified here

    0 讨论(0)
  • 2021-01-23 06:28

    This worked for me and I hope it will also work for you. In codeigniter 4 please use this to upload your files and move it in your controller.

    
    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
    
            }
        }
    }
    

    Or

    
            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
    
                }
            }
    
    

    Then in your html Use this

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

    I hope this will help you else call my attention.

    0 讨论(0)
提交回复
热议问题