本节将讲解如何上传文件
0.uploadPost.php
app/Views/uploadPost.php
<form method="post" action="" enctype="multipart/form-data">
<input type="text" name="title" required>
<input type="file" name="banner" required>
<input type="submit" name="" value="Send">
</form>
1.Dashboard.php里面的uploadPost
<?php namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\UsersModel;
use App\Models\PostsModel;
class Dashboard extends BaseController
{
public function index()
{
$model = new PostsModel();
$model->insert([
"banner"=>'img1.png',
"title"=>"My first post",
"intro"=>"Hello this is me",
"content"=>"Lorem ispsum bababa",
"category"=>"1",
"tages"=>"sports",
"created_at"=>date("Y-m-d"),
"created_by"=>"1"
]);
}
public function uploadPost()
{
if($_POST){
$file = $this->request->getFile("banner");
$filename = $file->getRandomName();
if($file->isValid()){
$file->move(WRITEPATH.'uploads',$filename);
}else{
echo 'NOT valid';
}
}
echo view('uploadPost');
}
}
里面的一个解释点在于WRITEPATH是Codeigniter 4自定义的一个文件夹,然后所有文件都导入到这里。操作成功后,app/writable/下会出现对应的文件。
没有多少演示的部分,大家可以试试。