升级上传文件处理
文档
变更点
文件上传的功能发生了很大变化。你现在可以检查文件是否成功上传,移动/存储文件也更简单了。
升级指南
在 CI4 中,通过 $file = $this->request->getFile('userfile')
访问上传的文件。然后可以使用 $file->isValid()
检验文件是否成功上传。
要存储文件,可以使用 $path = $this->request->getFile('userfile')->store('head_img/', 'user_name.jpg');
。这将文件存储在 writable/uploads/head_img/user_name.jpg。
你必须根据新方法更改文件上传代码。
代码示例
CodeIgniter 3.x 版本
<?php
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'png|jpg|gif';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if (! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
} else {
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
CodeIgniter 4.x 版本
<?php
namespace App\Controllers;
class Upload extends BaseController
{
public function index()
{
return view('upload_form', ['error' => ' ']);
}
public function do_upload()
{
$this->validateData([], [
'userfile' => [
'uploaded[userfile]',
'max_size[userfile,100]',
'mime_in[userfile,image/png,image/jpg,image/gif]',
'ext_in[userfile,png,jpg,gif]',
'max_dims[userfile,1024,768]',
],
]);
$file = $this->request->getFile('userfile');
if (! $path = $file->store()) {
return view('upload_form', ['error' => 'upload failed']);
}
$data = ['upload_file_path' => $path];
return view('upload_success', $data);
}
}