升级上传文件操作
文档
已更改内容
文件上传的功能已经发生了很大变化。现在,您可以检查文件是否已成功上传,而移动/存储文件也变得更加简单。
升级指南
在 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->validate([
'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);
}
}